converver多模型tovector<Key,Value>><vector<Value>>

问题描述 投票:0回答:2
转换为

std::vector<std::vector<T>>

。我需要这样做,因为我的程序需要对所有数据进行排序,并且地图无法对其进行排序。一个例子:
// Map:
{ "A", 1 },
{ "A", 3 },
{ "A", 2 },
{ "B", 5 }, 
{ "B", 2 },

// Map converted to vector<vector<Value>>:
{ 1, 3, 2 }, 
{ 5, 2 }
现在,我有此代码可行。但是我想知道这是否是最好的方法。

#include <unordered_map> #include <iostream> #include <string> #include <vector> int main() { typedef std::string Key_t; typedef int Value_t; typedef std::unordered_multimap<Key_t, Value_t> Map_t; const Map_t map = { { "A", 1 }, { "A", 3 }, { "A", 2 }, { "B", 5 }, { "B", 2 }, }; std::vector< std::vector< Value_t > > output; for ( Map_t::const_iterator it = map.cbegin(); it != map.cend(); ) { std::vector< Value_t > temp; const Map_t::const_iterator end = map.upper_bound( it->first ); for ( ; it != end; ++it ) temp.push_back( it->second ); output.push_back( temp ); } // Print the result for ( const std::vector< Value_t >& values : output ) { for ( const Value_t& value : values ) std::cout << value << " "; std::cout << std::endl; } }
输出:

1 3 2 5 2
,现在我想知道是否有更快/更好的方法。
    

在这里是我的尝试
#include <unordered_map> #include <iostream> #include <string> #include <vector> #include <algorithm> int main() { typedef std::string Key_t; typedef int Value_t; typedef std::unordered_multimap<Key_t, Value_t> Map_t; const Map_t map = { { "A", 1 }, { "A", 3 }, { "A", 2 }, { "B", 5 }, { "B", 2 }, }; std::vector< std::vector< Value_t > > output; for (auto it = map.begin(); it != map.end(); ) { auto er = map.equal_range(it->first); auto tmp = std::vector< Value_t >{}; for( ; it != er.second ; ++it) { tmp.push_back(it->second); }; output.push_back(std::move(tmp)); } // Print the result for ( const std::vector< Value_t >& values : output ) { for ( const Value_t& value : values ) std::cout << value << " "; std::cout << std::endl; } }

c++ c++11 stl c++14
2个回答
2
投票
通常的多模型迭代应在这里工作:

std::vector<std::vector<T>> out; for (auto it1 = m.begin(), it2 = it1, end = m.end(); it1 != end; it1 = it2) { out.emplace_back(); for ( ; it1->first == it2->first; ++it2) { out.back().push_back(it2->second); } }
    

1
投票

#include <vector> #include <iostream> #include <algorithm> #include <unordered_map> int main () { std::unordered_multimap<std::string, int> map; map = { { "A", 1 }, { "A", 3 }, { "A", 2 }, { "B", 5 }, { "B", 2 }, }; std::vector<int> values; std::transform(map.begin(), map.end(), std::back_inserter(values), [](std::pair<std::string, int> element) { return element.second; }); for (auto const& value : values) { std::cout << value << std::endl; } return 0; }

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.