为什么编译器说我不能将项插入到 std::set 中<Item>?
Why does the compiler say I can't insert an Item into a std::set<Item>?
我有一个名为"Item"的类,我正在尝试将一个项目插入到一组项目中。
std::set<Item>::iterator it;
_items.insert(it, newItem);
但它给了我这个奇怪的错误
Error 1 error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Item' (or there is no acceptable conversion)
即使我确实实现了这个运算符。
bool Item::operator<(Item& other)
{
return _serialNumber < other._serialNumber;
}
我不明白为什么我在这个函数中需要这个运算符。
有人知道问题出在哪里吗?
提前感谢!
您应该将定义更改为:-
bool Item::operator<( const Item& other) const
^^^^^ ^^^^^
{
return _serialNumber < other._serialNumber;
}
"我不明白为什么我在这个函数中需要这个运算符。
这是因为您需要确保在 Item
类的 rvalue 实例上调用此运算符函数。这是std::set
(以及其他容器类,其中Item
应用作键)的要求。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 为什么我无法更改"set<set>"循环中的值<int>
- 对于set上的循环-获取next元素迭代器
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 在声明中合并两个常量"std::set"(不是在运行时)
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将 std::set 与基于键的比较器一起使用
- 如何使用set实现无序数据结构?
- 使用运算符调用 void 函数时出错<set>
- 修改"std::set"中用户定义类型的值
- 生成提升::hana::set 的常量表达式问题
- 如何在构造函数参数中初始化"std::set"?
- 如何使用 lower_bound/upper_bound 从 std::set 获取索引号?
- 如何在 C++ 中转发声明 std::set?
- 重构使用动态强制转换的 std::set 的比较运算符
- set::find 查找不存在的元素
- 为什么 std::set.erase(first, last) 会影响从中获取 (first, last) 的容器?
- 是std :: set&lt; std :: future&gt;不可能存在