Sort the Map

I want to sort a map like map<int ,int > by its value .Kindly let suggest some efficient methods??

I think this is the best way.

bool cond(pair<int,int> a, pair<int,int> b) {
    if(a.second<b.second) return true;
    if(a.second==b.second && a.first<b.first) return true;
    return false;
}

//main function

map<int,int> M;
//fill map M
//transform map to vector of pair
vector<pair<int,int> > V(M.begin(),M.end());
sort(V.begin(),V.end(),cond);

You can transform map to vector of pairs and sort by second value of pair.

1 Like