2016-08-15 34 views
-3
struct node{ 
    int index; 
    int count; 
}; 

map<int,struct node *> m1; 

bool compare(struct node* a, struct node* b) { 
    if(a->count>b->count) 
     return 1; 
    if(a->count==b->count && a->index<b->index) 
     return 1; 
    return 0; 
} 

我可以根據更大的計數值對地圖進行排序,如果計數相等,則基於較低的索引值?如何基於C++中的值使用stl對映射進行排序?

一種方法是推送矢量中的所有值並執行排序。有沒有其他方式可以使用優先隊列進行排序,如下所示?

priority_queue<pair<int,struct node *>, vector<int,struct node *>, compare> pq(m1.begin(),m1.end()); 

我已經提供了上面的比較功能。

+5

'map'由鍵排序,不是值... – Jarod42

+5

的地圖已經排序,和它使用的密鑰(你的情況'int')要做到這一點排序。 – CoryKramer

+0

你不能'排序'一張地圖。 – NathanOliver

回答

0

解決方案priority_queue

class compare { 
    public: 
     bool operator()(pair<int,struct node *> a, pair<int,struct node *> b) { 
     if(a.second->count>b.second->count) 
      return 0; 
     if(a.second->count==b.second->count && a.second->index<b.second->index) 
      return 0; 
     return 1; 
     } 
    }; 

    priority_queue<pair<int,struct node *>, vector<pair<int,struct node *> >, compare > pq(m1.begin(),m1.end()); 
0

你可以嘗試使用Boost Multi-Index。一個索引提供地圖訪問,另一個提供有序的迭代器訪問。使用

相關問題