Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于值的C++ STL映射的排序_C++_C++11_Stl_Stdvector_Stdmap - Fatal编程技术网

基于值的C++ STL映射的排序

基于值的C++ STL映射的排序,c++,c++11,stl,stdvector,stdmap,C++,C++11,Stl,Stdvector,Stdmap,我有一张下面的地图: map<int, int> mp; mp[11] = 5; mp[3] = 7; mp[1] = 3; 但是我想知道哪个键的值比第一个出现的键的值大。 案例的输出示例: 3 7 11 5 1 3 我怎么能做到这一点呢?根据定义,你不能。映射是一种按键对其元素进行排序的数据结构。您可以反转键和值,并将它们插入到std::multimap中,然后可以遍历std::multimap,以获得所需顺序的值 map<int, int> mp;

我有一张下面的地图:

map<int, int> mp;
mp[11] = 5;
mp[3] = 7;
mp[1] = 3;
但是我想知道哪个键的值比第一个出现的键的值大。 案例的输出示例:

3 7
11 5
1 3

我怎么能做到这一点呢?

根据定义,你不能。映射是一种按键对其元素进行排序的数据结构。

您可以反转键和值,并将它们插入到std::multimap中,然后可以遍历std::multimap,以获得所需顺序的值

    map<int, int> mp;
    mp[11] = 5;
    mp[3] = 7;
    mp[1] = 3;
    std::multimap<int, int> mulp;
    std::transform(mp.begin(), mp.end(), std::inserter(mulp, mulp.begin()),
        [](const std::pair<int, int> &p){
            return std::make_pair(p.second, p.first);
        });
    for(auto it = mulp.rbegin(); it != mulp.rend(); ++it) {
        cout<<it->second<<" "<<it->first<<'\n';
    }


由于std::map只按键进行排序,因此您为需求选择了错误的容器

因此,您可以切换到使用std::vector,如:

包括 包括 int main{ std::向量v; v、 安置11,5; v、 炮位3、7; v、 炮位1,3; 排序 std::beginv,std::endv, []自动和左行,自动和右行{ 返回左秒>右秒; } ; 对于自动常数和i:v{
STD::是的。@ UlrichEckhardt,你是对的。检查你的问题的主题。这样做,删除在CPP上,这不是很精确,但可能更好地表达了C++标签在你的问题。@ UlrichEckhardt已经被编辑你仍然在问操作员过载。什么使你得出结论,这是相关的吗?我一直在尝试给你一个提示,就是你问的问题是错误的!而且,顺便说一下,在C++中删除,这就是标签的内容,在这个主题中不需要重复。
3 7
11 5
1 3
    map<int, int> mp;
    mp[11] = 5;
    mp[3] = 7;
    mp[1] = 3;
    std::multimap<int, int> mulp;
    std::transform(mp.begin(), mp.end(), std::inserter(mulp, mulp.begin()),
        [](const std::pair<int, int> &p){
            return std::make_pair(p.second, p.first);
        });
    for(auto it = mulp.rbegin(); it != mulp.rend(); ++it) {
        cout<<it->second<<" "<<it->first<<'\n';
    }

3 7
11 5
1 3