如何使用std :: greater对C++映射键进行排序?

Exu*_*ery 6 c++

我正在创建一个std::map<int, int>C++,我更喜欢让它们从最高到最低排序,而不是默认的排序顺序.我的研究引导我到std :: more这看起来很有希望但是在尝试使用它时我遇到了编译错误:

一元'*'的无效类型参数(有'int')

我的地图声明是:

std::map<int, int, std::greater<int> > numMap;
Run Code Online (Sandbox Code Playgroud)

而且这个函数抛出了错误:

void Row::addNumber(int num, int pos) {
    numMap.insert(num, pos);
}
Run Code Online (Sandbox Code Playgroud)

这样的类似问题的答案包括声明中的括号,即std :: greater () - 但是当我包含那些时,我得到关于返回函数的函数的多个错误.

Ser*_*nov 7

问题 - std::map::insert使用无效参数调用成员函数:提供了两个整数值; 但必须有 std::pair<int, int>.请参阅参考:std :: map :: insert.

优先选择

方便起见(只是不重复地图类型参数),typedef为地图创建一个:

typedef std::map<int, int> IntMap;
Run Code Online (Sandbox Code Playgroud)

std::map进行了类型定义std::pair(对表示) - std::map::value_type.因此,举例来说,如果有一个std::map<int, int>std::map::value_typestd::pair<int, int>.

使用std::map::value_type构造函数(IntMap::value_type在本例中):

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;
};
Run Code Online (Sandbox Code Playgroud)

备择方案:

  1. 使用std::make_pair()功能:

    #include <utility>
    
    ...
    
    void Row::addNumber(int num, int pos)
    {
        numMap.insert(std::make_pair(num, pos));
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 直接使用std::pair构造函数:

    void Row::addNumber(int num, int pos)
    {
        numMap.insert(std::pair<int, int>(num, pos));
    }
    
    Run Code Online (Sandbox Code Playgroud)


ela*_*dan 5

比谢尔盖的答案(这也肯定有效)更迂腐,而不是使用:

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));
}
Run Code Online (Sandbox Code Playgroud)

好处是,如果您更改地图的类型,您可以减少以后更改的代码.并且更不可能但仍然可能,如果实施std::map将其value_typestd::pair其他地方(在未来的版本中stl)更改,则您不会受到这种变化的影响.