如何计算c ++ stl设置工作?

sha*_*har 3 c++ count set

所以,我正在尝试检查集合中是否已存在特定对象.为此,我使用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;
};
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我声明了一个这样的集合 -

set<Node*> myset;
Run Code Online (Sandbox Code Playgroud)

在几次插入之后,myset就像这样{{1,5},{2,6},{3,9}}

现在我检查{1,7}是否是该集合的一部分.它会怎么做?我在Node类中编写了一个operator ==方法,它从不被调用.然后在什么基础上count()检查对象是否已经在集合中?...我希望计数以一种方式工作,如果{1,5}已经存在于myset中,它应该查看{1, 7}作为重复条目.

Lig*_*ica 7

如何计算c ++ stl设置工作?

operator<默认使用.

实际上,通常,C++标准库容器用于!(a < b) && !(b < a)确定等价的属性.

您可以通过为Compare容器类型提供自己的模板参数来覆盖用于执行此检查的比较器,尽管很少有理由 - 您通常应该只operator<为您的类型定义,就像您所做的那样.(但要确保它创建了严格的弱排序.)

在我的代码中,我声明了一个这样的集合 -

set<Node*> myset;
Run Code Online (Sandbox Code Playgroud)

在几次插入之后,myset就像这样{{1,5},{2,6},{3,9}}

不,你的套装绝不是这样的.你的集合包含指针,而不是Nodes.set<Node>改为做一个.