因此,我正在尝试检查特定对象是否已存在于集合中。为此,我使用 count() 方法。现在,它似乎没有返回正确的答案。让我更清楚地解释一下这个问题 --
我已经这样声明了一个类
class Node{
public:
Node(int _state=0, int _cost=0)
{
state = _state;
cost = _cost;
}
bool operator<(const Node& rhs)
{
return cost < rhs.cost;
}
bool operator==(const Node& rhs)
{
cout << "== operator method used" << endl;
if (rhs.state == state)
return true;
return false;
}
int state;
int cost;
};
在我的代码中,我声明了这样一个集合——
set<Node*> myset;
插入几次后,myset 是这样的 {{1, 5}, {2, 6}, {3, 9}}
现在我检查 {1, 7} 是否是集合的一部分。它是怎么做到的?我在 Node 类中编写了一个 operator== 方法,它从未被调用过。那么 count() 在什么基础上检查对象是否已经在集合中?...我希望计数以一种方式工作,如果 {1, 5} 已经存在于我的集合中,它应该查看 {1, 7} 作为重复条目。
最佳答案
how does count in c++ stl set work?
它使用 operator<
默认情况下。
其实一般来说,C++标准库容器使用!(a < b) && !(b < a)
确定等价的性质。
您可以通过提供自己的 Compare
来覆盖用于执行此检查的比较器容器类型的模板参数,尽管很少有理由这样做——您通常应该简单地定义 operator<
为你的类型,就像你所做的那样。 (尽管如此,请确保它创建了一个 Strict Weak Ordering。)
in my code, I declare a set like this --
set<Node*> myset;
after a few insertions, myset is like this {{1, 5}, {2, 6}, {3, 9}}
不,你的集合从来都不是这样的。你的集合包含指针,而不是Node
秒。让它成为 set<Node>
相反。
关于c++ - C++ STL set 中的计数是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8118148/