Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i sort a map by its .second parameter [duplicate]

Tags:

If i have a stl map from string to int and i want to print all the int values sorted - how can i do that?

like image 979
amitlicht Avatar asked Mar 16 '10 10:03

amitlicht


People also ask

How do you sort a map by value?

Example: Sort a map by values Inside the method, we first created a list named capitalList from the map capitals . We then use the sort() method of Collections to sort elements of the list. The sort() method takes two parameters: list to be sorted and a comparator. In our case, the comparator is a lambda expression.

How do you sort a map using comparator?

Sort HashMap by Values using Comparator Interface After that get the Set of elements from the Map and convert Set into the List. Use the Collections. sort(List) method to sort the list of elements by values by passing customized comparator. Now create a new LinkedHashMap and copy the sorted elements into that.

Can we sort map in CPP?

You cannot sort a map, it's an associative container, not a sequential, and associated containers are sorted by some internal order. If you want to only print the int values, you could put them into a std::vector , sort the vector, and print the values.

Is it possible to sort the entries in map based on the values rather than by keys?

The difference between sorting HashMap by Keys and Values is that it can have duplicate values but not duplicate Keys. We cannot use TreeMap to sort values because TreeMap sorts elements by Keys.


2 Answers

You cannot sort a map by its values due to the implementation of the map.

If you want to emit the elements in the map in such a sorted order then you have to first dump the map contents into a vector (say) and sort that vector:

template <typename T1, typename T2> struct less_second {     typedef pair<T1, T2> type;     bool operator ()(type const& a, type const& b) const {         return a.second < b.second;     } };  map<string, int> mymap; // …  vector<pair<string, int> > mapcopy(mymap.begin(), mymap.end()); sort(mapcopy.begin(), mapcopy.end(), less_second<string, int>()); 

Or alternatively, just copy the values from the map, leaving the keys, and sort the resulting vector directly.

like image 110
Konrad Rudolph Avatar answered Sep 23 '22 10:09

Konrad Rudolph


You can copy all the values into vector and sort it.

#include <algorithm> #include <map> #include <vector>  int get_second( pair<string, int> i ){ return i.second; }  int main(int argc, char* argv){   map<string, int> m;   m["tt"] = 2;   m["rr"] = 1;   m["ee"] = 3;    vector<int> v( m.size() );   transform( m.begin(), m.end(), v.begin(), get_second );   sort( v.begin(), v.end() );   for (int i=0; i<v.size(); i++) cout << v[i] << endl; } 
like image 29
Draco Ater Avatar answered Sep 23 '22 10:09

Draco Ater