std::map 插入错误:没有运算符"<"与这些操作数匹配
std::map insert error: no operator "<" matches these operands
试图复习我的C++和STL熟练程度,遇到了由我定义的结构键控的std::map的问题。相关代码:
typedef struct key_t {
int a;
int b;
bool operator==(const key_t& rhs)
{
return (a == rhs.a) && (b == rhs.b);
}
bool operator<(const key_t& rhs) //added the when I saw this error, didn't help
{
return a < rhs.a;
}
} key_t;
std::map<key_t, int> fooMap;
void func(void)
{
key_t key;
key.a = 1;
key.b = 2;
fooMap.insert(std::pair<key_t, int>(key, 100));
}
错误如下所示:
"/opt/[redacted]/include/functional", line 133: error: no operator "<" matches these operands
operand types are: const key_t < const key_t
detected during:
instantiation of "bool std::less<_Ty>::operator()(const _Ty &, const _Ty &) const [with _Ty=key_t]" at line 547 of "/opt/[redacted]/include/xtree"
instantiation of "std::_Tree<_Traits>::_Pairib std::_Tree<_Traits>::insert(const std::_Tree<_Traits>::value_type &) [with _Traits=std::_Tmap_traits<key_t, UI32, std::less<key_t>, std::allocator<std::pair<const key_t, UI32>>, false>]"
我做错了什么?使用结构作为地图键只是非常糟糕/不可能吗?还是我忽略了什么?
bool operator<(const key_t& rhs)
需要是一个常量方法
bool operator<(const key_t& rhs) const
两者是不同的签名,std::less
寻找后者。后者作为 const 方法,暗示它不会修改对象。然而,前者没有常量可能意味着可以对this
进行修改。
一般来说,拥有const
方法是个好主意,即使你可以放弃,这也意味着向客户承诺不会进行任何修改。
对于初学者来说,运算符必须const
. (而且您不需要==
运算符。
你从哪里学会将 typedef 用于struct
. 没有理由。
最后,如果您希望这两个元素都作为关键,你必须比较它们:
struct Key
{
int a;
int b;
bool operator<( Key const& rhs ) const
{
return a < rhs.a
|| ( !(rhs.a < a) && b < rhs.b );
}
};
否则,Key( 1, 2 )
和Key( 1, 3 )
将有效地平等。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 控制允许动态运行c++的并发操作数
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- <<操作员在下面的行中工作
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C++ 带有向量的 IF 计算操作数
- 是否所有C++运算符都接受操作数?
- 一元*运算符的操作数是否期望一个 prvalue
- 与'operator='不匹配(操作数类型'String'且"void")
- 不正确的操作数类型 MSVC
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 没有运算符"="与这些操作数匹配,JUCE 窗口演示应用程序
- 如果我在指针中使用 ++ 操作数,我的值就会出错
- 二进制表达式的操作数无效 - 使用 for 和迭代器
- C2679 二进制"<<":未找到采用右操作数类型的运算符
- CPP 运算符重载操作数位置 [] 与 ==