我正在尝试编写 C++ STL 集,它保留指向我的自定义类的指针。但我不明白当我使用指针而不是类的对象时如何重载
我读到,如果我们重载 set 用于比较的
当您使用operator()函数创建一个结构并将其传递给集合时,我遇到了这个技巧,例如set<Object, Comparator>
。但我仍然不明白它是如何工作的,因为 set 只使用 less-comparison。
#include <iostream>
#include <set>
using namespace std;
class Node
{
int x;
public:
Node(int x)
{
this->x = x;
}
bool operator<(const Node& n) const
{
cout << "inside operator<" << endl;
return this->x < n.x;
}
};
int main()
{
set<Node*> s;
Node n1(10);
Node n2(11);
s.insert(&n1);
auto res = s.find(&n1);
if (res == s.end())
{
cout << "not found";
}
else
{
cout << "found";
}
return 0;
}
代码结果为found
. Why?
我乐意去学:
- How use
set
与指针。
- 如何超载
operator<
适当地。
You 可能不会想要改变bool operator <(Node *, Node *)
。相反,您应该寻求提供非默认的Compare给你的set
.
template <typename T>
struct pointee_less
{
bool operator()(T* lhs, T* rhs) const
{
return (lhs && rhs) ? std::less<T>{}(*lhs, *rhs) : std::less<T*>{}(lhs, rhs);
}
}
template <typename T>
using pointer_set = std::set<T*, pointee_less<T>>;
int main()
{
pointer_set<Node> s;
Node n1(10);
Node n2(11);
s.insert(&n1);
auto res = s.find(&n1);
if (res == s.end())
{
cout << "not found";
}
else
{
cout << "found";
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)