获取按地图值排序的映射键向量的最快方法
Fastest way to get a vector of map keys sorted by map values?
我有一个map<int int>
.我需要获取第一个 int(键)的向量,但按第二个 int 的顺序(值)排序。最快的方法是什么?
任何告诉你他们有"最快"方法的人都是骗子,因为他们不知道你正在使用什么硬件/C++实现等。
这是一种方法:
typedef pair<int,int> item;
vector<item> mytmp(mymap.begin(), mymap.end());
sort(mytmp.begin(), mytmp.end(), [](item lhs, item rhs) { return lhs.second < rhs.second; });
vector<int> myvec;
myvec.reserve(mytmp.size());
transform(
mytmp.begin(), mytmp.end(),
back_inserter(myvec);
[](item i) { return i.first; }
);
您可以创建第二个映射,在其中交换<key,value>
对以<value,key>
。但是,如果您有重复的值,则会遇到麻烦。
您实际上想要的可能是一个双向地图。 例如,请参阅 http://www.boost.org/doc/libs/1_47_0/libs/bimap/doc/html/index.html。
您可以将其放入std::vector<std::pair<int, int> >
,然后编写一个谓词以对第二个值进行排序。 然后通过密钥对中的第一个值访问密钥:
std::map<int, int> the_map;
typedef std::pair<int,int> pair_type;
the_map[1] = 2;
the_map[2] = 1;
the_map[3] = 8;
the_map[4] = 8;
the_map[5] = 3;
struct Pred {
bool operator()(pair_type const& a, pair_type const& b) const {
return (a.second < b.second);
}
};
struct Tran {
int operator()(pair_type const& a) const {
return a.first;
}
};
std::vector<pair_type> vec(the_map.begin(), the_map.end());
std::sort(vec.begin(), vec.end(), Pred());
std::vector<int> result;
transform(vec.begin(), vec.end(), std::back_inserter(result), Tran());
BOOST_FOREACH(int const& r, result) {
cout << r << endl;
}
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 声明高维向量的更简洁的方法
- 在C++中初始化向量映射的最有效方法
- C++11 迭代向量的新方法?
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 有什么方法可以将具有不同模板参数的模板类实例放入向量中?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 访问类成员向量最后一项的正确方法
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 检查两个向量是否并行的最有效方法
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 返回向量元素的 l 值的正确方法是什么?
- 如何在方法主体中返回声明向量的引用?