【发布时间】:2015-04-12 20:08:53
【问题描述】:
我需要将std::unordered_multimap<Key,T> 转换为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
所以,现在我想知道是否有更快/更好的方法。
【问题讨论】:
-
我认为
typedef std::string Value_t;应该是一个整数类型(例如,int).. -
@JamesAdkison 哦,对。固定。
-
不,再次检查,在
unordered_map或unordered_multimap的标准规范中没有upper_bound。确定您使用的是无序变体? (在修复缺少的<vector>包含后,代码也无法使用 libstdc++ 或 libc++ 编译。) -
unordered map 被记录为具有
equal_range函数但没有上限或下限,这使得它依赖于排序顺序。 -
@Xeo 我 100% 确定我正在使用
unordered_multimap,并且我的代码正在 Visual Studio 2013 上编译和运行。