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?
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.
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With