gpt4 book ai didi

c++ - 为一组 C++ 指针定义 operator<

转载 作者:行者123 更新时间:2023-11-28 01:18:17 25 4
gpt4 key购买 nike

我正在尝试编写 C++ STL 集,它保留指向我的自定义类的指针。但是当我使用指针而不是类的对象时,我不明白如何重载 < 运算符。

我读到如果我们重载 set 用于比较的 < 运算符。但是当我存储指针时,这个函数根本不会被调用。这意味着 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 .为什么?

我想学习:

  • 如何使用set有指点。
  • 如何重载operator<

最佳答案

可能不想改变bool operator <(Node *, Node *) .相反,您应该寻求为您的 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;
}

关于c++ - 为一组 C++ 指针定义 operator<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57852469/

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