2017-07-10 67 views
-2

我創建了Cmp()函數來用作Comparator.But Iam出錯。 我寫了這個代碼。它顯示錯誤:如何根據第二個元素對映射<int,對<int,int>>進行排序?

#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; 
} 

它提供了錯誤:

In member function 'bool cmp::operator()(std::multimap >, std::multimap >)':

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

有沒有使用結構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. 
+1

您無法按照其值對地圖進行排序。也許你正在尋找一個'std :: set'而不是?你是否想要反轉你的鑰匙和你的價值? –

+0

您沒有通過指針而是通過值來傳遞函數operator()。所以像'a-> second.second'這樣的尋址無效。你爲什麼不嘗試通過參考。 –

+0

好的..我要去std :: set ...謝謝 – unknown

回答

1

該問題的基礎沒有意義。從cppreference

The order of the key-value pairs whose keys compare equivalent is the order of insertion and does not change.

你不能支配的順序。如果您需要對它們進行排序,則需要先將它們複製到新的容器中,或者將它們放入新的容器中以便開始。

而且,Compare類型,而不是整個地圖進行比較。鏈接的參考文件中也有示例。

相關問題