gpt4 book ai didi

c++ - 在 C++ 集合中查找相等的实例

转载 作者:行者123 更新时间:2023-11-30 01:15:41 25 4
gpt4 key购买 nike

我正在使用 C++ STL 集,我想知道它是否存在于该集中的等效实例中。要检索实例,我正在使用查找集方法。问题是它不起作用。我认为问题出在我的比较对象中:

bool SetComparator::operator ()( const Point* i1, const Point* i2 ) const {
if ( *i1 == *i2 )
return false;
return true;
}

运算符 == 以简单的方式为类 Point 重新定义:

bool Point::operator ==( const Point& p ) const {
if (x == p.x && y == p.y)
return true;
return false;
}

调试后我可以看到 find 方法调用了 operator() 但它没有找到相同的实例,因此 find 返回 end() 但我知道有一个相等的对象。我认为问题与设置的内部顺序有关。我该怎么办?

最佳答案

std::set 使用偏序(即 operator< ),因此当您传入只能决定相等性的运算符时,您打破了 std::set 实现的假设。您的 SetComparator 的行为必须类似于 std::less .

例如 std::pair(实用程序)实现 relational operators对于两个项目,例如对于 operator< :

template <class T1, class T2>
bool operator< (const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs) {
return lhs.first<rhs.first || (!(rhs.first<lhs.first) && lhs.second<rhs.second);
}

请注意 (!(rhs.first<lhs.first) && lhs.second<rhs.second)(rhs.first == lhs.first && lhs.second < rhs.second) 的解决方法仅使用 operator<

如果您只想检查是否相等,使用 std::set 可能是错误的决定。如果你可以散列你的对象,你可以使用 std::unordered_set (C++11 及更高版本)。

关于c++ - 在 C++ 集合中查找相等的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28063299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com