How to sort C ++ map keys using std :: more?

I create std::map<int, int> in C ++, which I would prefer them to sort the keys from highest to lowest, rather than the default sort order. My research led me to std :: more , which looked promising, but when I try to use it, I get a compilation error:

invalid unary type argument '* (have' int)

My card ad:

 std::map<int, int, std::greater<int> > numMap; 

And this error arises from this function:

 void Row::addNumber(int num, int pos) { numMap.insert(num, pos); } 

Answers to similar questions such as this include brackets in the declaration, that is, std :: is larger () , but when I include those I get a few errors regarding the function returning the function.

+6
source share
2 answers

The problem is the call to the std::map::insert member function with invalid parameters: there are two integer values; but there should be std::pair<int, int> . See Link: std :: map :: insert .

Preferred option

For convenience (just do not repeat the parameters of the map type) create a typedef for the map:

 typedef std::map<int, int> IntMap; 

std::map has a type definition for std::pair (pair representation) - std::map::value_type . So, for example, if there is std::map<int, int> , then std::map::value_type will be std::pair<int, int> .

Use the constructor std::map::value_type ( IntMap::value_type in this case):

 class Row { public: void Row::addNumber(int num, int pos) { m_numMap.insert(IntMap::value_type(num, pos)); } private: typedef std::map<int, int> IntMap; IntMap m_numMap; }; 

Alternatives:

  • Use the std::make_pair() function:

     #include <utility> ... void Row::addNumber(int num, int pos) { numMap.insert(std::make_pair(num, pos)); } 
  • Use the std::pair constructor directly:

     void Row::addNumber(int num, int pos) { numMap.insert(std::pair<int, int>(num, pos)); } 
+7
source

A little more pedantic than Sergey's answer (which also definitely works), use:

 typedef std::map<int, int, std::greater<int> > MyMap; MyMap numMap; void Row::addNumber(int num, int pos) { numMap.insert(MyMap::value_type(num, pos)); } 

The advantage is that if you change the type of card, you have less code to change it later. And much less likely, but still possible, if the implementation of std::map changes its value_type from std::pair to something else (in a future version of stl ), you are immune to this change.

+5
source

All Articles