【发布时间】:2021-02-19 23:55:22
【问题描述】:
我正在尝试实现一个std::set::insert,这样它就会“插入”一个结构,因为它还不存在。
我已经为“小于”添加了所需的自定义运算符重载 (<);然而,当代码被执行时,它似乎只是跳过它并且不能按预期工作。 (修改的实现(添加的const noexcept 取自这里:C2676: binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator)
示例代码:
#include <set>
struct Coordinate
{
int x;
int y;
Coordinate(int x = 0, int y = 0) : x(x), y(y)
{
}
bool operator==(const Coordinate& obj)
{
return x == obj.x && y == obj.y;
}
bool operator!=(const Coordinate& obj)
{
return x != obj.x && y != obj.y;
}
bool operator< (const Coordinate& obj) const noexcept
{
return x < obj.x && y < obj.y;
}
};
int main(){
std::set<Coordinate> current_set = {Coordinate(1, 2)};
Coordinate new_coordinate(1, 3);
current_set.insert(new_coordinate);
}
需要明确的是,通过此实现,即使成员明显不同,该集合也不会使用 new_coordinate 对象进行更新。
如有任何帮助,我们将不胜感激。
【问题讨论】:
-
嗨,从我读到的内容看来,它至少是排序的(en.cppreference.com/w/cpp/container/set)。我相信您也可以为此使用 unsorted_set 。你以前遇到过这个问题吗?
标签: c++ set operator-overloading