Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 类,该类包含一组具有自定义比较器(循环引用)的自身_C++_Templates_Set - Fatal编程技术网

C++ 类,该类包含一组具有自定义比较器(循环引用)的自身

C++ 类,该类包含一组具有自定义比较器(循环引用)的自身,c++,templates,set,C++,Templates,Set,目标如下(当然,代码简化): 有更好的办法吗?如果答案在节点为内部类时仍然有效,则可获得额外积分。您可以使用嵌套类作为比较器: #include <set> struct Node { struct CompareNodes { bool operator()(const Node& l, const Node& r) { return l.Value < r.Value; } };

目标如下(当然,代码简化):


有更好的办法吗?如果答案在
节点
为内部类时仍然有效,则可获得额外积分。

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

#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;
};
#包括
结构体类型
{
结构比较节点
{
布尔运算符()
{
返回l.值
转发声明在这两种情况下都没有帮助

不完全正确。远期申报将很好地发挥作用:

#include <set>

struct Node;

struct CompareNodes
{
    bool operator()(const Node& l, const Node& r);
};

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

bool CompareNodes::operator()(const Node& l, const Node& r)
{
    return l.Value < r.Value;
}
#包括
结构节点;
结构比较节点
{
布尔运算符()(常量节点和l、常量节点和r);
};
结构体类型
{
int值;
性病:集合儿童;
};
布尔比较节点::运算符()
{
返回l.值

如果需要在头文件中声明
operator()
成员函数,则有必要在其上粘贴
inline
关键字。

也许您可以利用模板将完整性检查延迟到使用前

#include <set>

struct CompareNodes;

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

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

int main() {
    Node<> n;
}
#包括
结构比较节点;
模板
结构体类型
{
int值;
性病:集合儿童;
};
结构比较节点
{
布尔运算符()(常数节点*l,常数节点*r)
{
返回l->ValueValue;
}
};
int main(){
节点n;
}

无论如何,您都不能创建不完整类型的标准库容器,至少不能进行移植。简单地说,您不能有一个包含一组自身的类。@juanchopanza Hm。它可能不可移植,但我的编译器允许。如果我将它更改为
std::set
,它是否仍然算作不完整的类型?那就好了。或者使用boost.container库中的
boost::set
。我相信
sts::set
需要
Node
才能成为完整的类型?还是最近有所改变?
#include <set>

struct Node;

struct CompareNodes
{
    bool operator()(const Node& l, const Node& r);
};

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

bool CompareNodes::operator()(const Node& l, const Node& r)
{
    return l.Value < r.Value;
}
#include <set>

struct CompareNodes;

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

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

int main() {
    Node<> n;
}