Can't compile std :: map collation, why?

This is my code:

map<string, int> errs; struct Compare { bool operator() (map<string, int>::const_iterator l, map<string, int>::const_iterator r) { return ((*l).second < (*r).second); } } comp; sort(errs.begin(), errs.end(), comp); 

Unable to compile. This is what I get:

 no matching function for call to 'sort(..' 

Why is that? Can anyone help? Thanks!

+4
source share
7 answers

Cards, by definition, are sorted by their keys, so you cannot resort to a card by its values.

You can provide an alternative comparison function as the third template parameter for the card if you want to sort the keys in a non-standard order.

If you are trying to sort a map by its values, then perhaps you could try using Boost.MultiIndex to make a bi-directional map instead?

+6
source

You cannot sort the map. It has its own sort order, defined during construction either by default (use < ) or passed in a comparator.

+10
source

I assume you are doing using namespace std; . This sort method requires iterators to be random access iterators. But map iterators are bidirectional, so they wonโ€™t compile.

+5
source

This is probably due to the fact that std :: map has an unassigned iterator.

std :: map has an invariant that strictly increases; it is always sorted by key.

Read more about this here: http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html

and note 1 here: http://www.sgi.com/tech/stl/Map.html

+4
source

In addition to Marceloโ€™s answer: the predicate used by std :: sort should take values, not iterators, as input.

+1
source

As stated in Marcelo, you cannot sort a map with std :: sort, you need to define a sorting method in the constructor, which, in my opinion, is value_compare.

 struct Compare { bool operator()(const char* a, const char* b) const { return strcmp(a,b) < 0; }; std::map<char, char, Compare> compareMap; 
0
source

The Compare template parameter accepts map keys for comparison (or shortcuts to keys), not iterators. In addition, std::map accepts this type when creating an instance and is automatically sorted by key (the most common version is red-black tree ).

See boost::multi_index for multi-key access.

0
source

Source: https://habr.com/ru/post/1310111/


All Articles