我正在创建一个std :: map< int,int>在C中,我更喜欢将键从最高到最低排序,而不是默认的排序顺序.我的研究引导我到
std::greater看起来很有希望,但在尝试使用它时我得到一个编译错误:
invalid type argument of unary ‘*’ (have ‘int’)
我的地图声明是:
std::map<int,int,std::greater<int> > numMap;
而且这个函数抛出了错误:
void Row::addNumber(int num,int pos) {
numMap.insert(num,pos);
}
对类似问题(如this)的回答包括声明中的括号,即std :: greater() – 但是当我包含那些时,我得到关于返回函数的函数的多个错误.
解决方法
问题 – 使用无效参数调用std :: map :: insert成员函数:提供了两个整数值;但必须有std :: pair< int,int>.请参阅参考:
std::map::insert.
优先选择
为方便起见(只是不重复地图类型参数),为地图创建一个typedef:
typedef std::map<int,int> IntMap;
std :: map具有std :: pair(对表示)的类型定义–std :: map :: value_type.
所以,例如,如果有一个std :: map< int,int> std :: map :: value_type将是std :: 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;
};
备择方案:
>使用std :: make_pair()函数:
#include <utility>
...
void Row::addNumber(int num,int pos)
{
numMap.insert(std::make_pair(num,pos));
}
>直接使用std :: pair构造函数:
void Row::addNumber(int num,int pos)
{
numMap.insert(std::pair<int,int>(num,pos));
}