【问题标题】:Why does the compiler say I can't insert an Item into a std::set<Item>?为什么编译器说我不能将 Item 插入 std::set<Item>?
【发布时间】:2015-01-08 16:59:56
【问题描述】:

我有一个名为“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;
}

我不明白为什么我在这个函数中需要这个运算符。

有人知道问题出在哪里吗?

提前致谢!

【问题讨论】:

  • 提示在错误中:'const Item',您的操作员应该通过 const ref 取其他。 (您可能也应该将运算符设为 const)
  • 实现 bool Item::operator
  • 另外,您的 it 迭代器没有引用任何内容,但您在 insert 调用中使用了它。
  • @AlonPe'er 那将是一个完全不同的问题(Paul 的评论可能涵盖了这个问题)。建议您阅读std::set并且永远不要更改已发布问题的基本上下文!您只是使所有已发布的答案和 cmets 在现在发布的文本的上下文中完全没有意义。如果有其他问题,请发布新问题。
  • @WhozCraig 同意。回滚到您的版本。

标签: c++ stl insert set operator-keyword


【解决方案1】:

您应该将定义更改为:-

bool Item::operator<( const Item& other)  const
                      ^^^^^               ^^^^^
{
    return _serialNumber < other._serialNumber;
}

【讨论】:

  • 谢谢,但现在它崩溃了...... :(
  • 是时候调试它并在问题仍然存在时提出另一个问题:)
【解决方案2】:

“我不明白为什么我在这个函数中需要这个运算符。”

这是因为您需要确保在 Item 类的 rvalue 实例上调用此运算符函数。这是std::set 中的requirement(以及其他容器类,其中Item 应该用作键)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2021-10-08
    • 1970-01-01
    • 2011-08-29
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多