【问题标题】:How to sort map<int,pair<int,int> > according to second element only?如何仅根据第二个元素对 map<int,pair<int,int>> 进行排序?
【发布时间】:2017-07-10 17:19:39
【问题描述】:

我创建了 Cmp() 函数用作比较器。但我遇到了错误。 我已经写了这段代码。它显示错误:

#include<bits/stdc++.h>
using namespace std;
struct cmp
    {
        bool operator() (multimap<int,pair<int,int> > a, multimap<int,pair<int,int> > b)
            {
                if(a->second.second>b->second.second)
                    return 1;
                return 0;
            }
    };
int main()
{
    std::ios::sync_with_stdio(false);
    int test,i;
    long long sum=0;
    cin>>test;
    while(test--)
    {
        multimap<int, pair<int,int>,cmp > mymap;
        multimap<int, pair<int,int> >::iterator it;
        int n,days,d,t,s;
        cin>>n>>days;
        for(i=0;i<n;i++)
        {
            cin>>d>>t>>s;
            mymap.insert(make_pair(d,make_pair(t,s)));
        }
        for(it=mymap.begin();it!=mymap.end();it++)
        {
            cout<<it->first<<"  "<<it->second.first<<" "<<it->second.second<<endl;
        }

    }
    return 0;
}

它给出了错误:

在成员函数'bool cmp::operator()(std::multimap >, std::multimap >)'中:

 [Error] base operand of '->' has non-pointer type 'std::multimap<int, 
std::pair<int, int> >'

不使用struct Cmp()函数还有其他方法吗?

eg:- suppose i have

(3,(2,300))
(3,(1,400))
(3,(2,500))
(2,(3,100))
(2,(2,500))
(1,(5,100))

I want output like this:
(1,(5,100))
(2,(2,500))
(2,(3,100))
(3,(2,500))
(3,(1,400))
(3,(2,300))

   Only the second element of pair<int,int> sorted decreasingly.

【问题讨论】:

  • 您不能按地图的值对地图进行排序。也许您正在寻找std::set?您的意思是反转您的密钥和值吗?
  • 您不是通过指针而是通过值传递给函数operator()。所以像a-&gt;second.second 这样的地址是行不通的。你为什么不尝试通过引用传递。
  • 好的..我要去 std::set...谢谢
  • &lt;bits/stdc++.h&gt; 是 (a) 不是标准文件,并且 (b) 是一种不好的做法,因为使用它您无法学习单独包含标准库的各个部分。见stackoverflow.com/questions/25311011/…

标签: c++ stl c++14


【解决方案1】:

问题的基础没有意义。来自cppreference:

其键比较相等的键值对的顺序是插入的顺序,不会改变。

您不能指定值的顺序。如果您需要对它们进行排序,则需要先将它们复制到新容器中,或者先将它们放入新容器中。

另外,Compare 类型比较键,而不是整个地图。链接参考中也有示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多