c++ - 包含一组自身和自定义比较器的类——循环引用

标签 c++ templates set

这是目标(当然是简化了代码):

#include <set>

struct Node
{
   int Value;
   std::set<Node*, CompareNodes> Children;
};

struct CompareNodes
{
   bool operator()(const Node* l, const Node* r)
   {
      return l->Value < r->Value;
   }
};

但这不能编译; CompareNodes 类型在 Node 内部遇到时是未知的。我可以颠倒顺序,但我遇到了相反的问题——NodeCompareNodes 中遇到时是未知的。在这两种情况下,前向声明都无济于事,因为每种类型都以需要其完整定义的方式使用另一种类型。一个丑陋的解决方法是:

#include <set>

template<typename T>
struct CompareNodes
{
   bool operator()(const T* l, const T* r)
   {
      return l->Value < r->Value;
   }
};

struct Node
{
   int Value;
   std::set<Node*, CompareNodes<Node>> Children;
};

有没有更好的方法?如果即使 Node 是内部类,答案仍然有效,则加分。

最佳答案

您可以使用嵌套类作为比较器:

#include <set>

struct Node
{
   struct CompareNodes
   {
      bool operator()(const Node& l, const Node& r)
      {
         return l.Value < r.Value;
      }
   };

   int Value;
   std::set<Node, CompareNodes> Children;
};

关于c++ - 包含一组自身和自定义比较器的类——循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40750630/

相关文章:

python - Jinja2 网络自动化 - 增加一个变量(子网+1)

java - ArrayList 在运行方法后不会返回修改后的值

java - HashSet 包含对象的副本

performance - 查找集合成员的有效方法

c++ - 编写代码帮助编译器进行优化

c++ - 使用另一个参数的默认参数

c++ - constexpr 函数调用无法编译

c++ - boost::iostreams::filtering_stream 的底层流的类型是什么?

c++ - 为什么在类模板的显式实例化之前需要外部类模板的显式实例化

templates - 用于 CSV 导入的 Libreoffice Calc 模板