获取按地图值排序的映射键向量的最快方法

Fastest way to get a vector of map keys sorted by map values?

本文关键字:向量 方法 映射 地图 排序 获取      更新时间:2023-10-16

我有一个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;
}