繁体   English   中英

如何在同一个结构中声明结构的向量?

[英]How do I declare a vector of a struct within that same struct?

我正在尝试创建一个结构,其中包含一个类型为相同结构的向量。 但是,当我构建时,错误表明我错过了';' 在'>'出现之前。 我不确定编译器是否甚至认为向量是一个东西:/并且我已经包含在我的代码中。 这是我到目前为止:

#include <vector>

typedef struct tnode
{
    int data;
    vector<tnode> children;
    GLfloat x; //x coordinate of node 
    GLfloat y; //y coordinate of node
} tnode;

任何帮助将不胜感激!!

您的代码正在调用未定义的行为,因为诸如vector标准容器不能包含不完整的类型,而tnode在结构定义中是不完整的类型。 根据C ++ 11标准,17.6.4.8p2:

在以下情况下,效果未定义:[...]如果在实例化模板组件时将不完整类型(3.9)用作模板参数,除非特别允许该组件。

Boost.Container库提供了可以包含不完整类型的备用容器(包括vector )。 递归数据类型(例如您想要的类型)将作为此用例给出。

以下内容适用于Boost.Container:

#include <boost/container/vector.hpp>
struct tnode
{
    int data;

    //tnode is an incomplete type here, but that's allowed with Boost.Container
    boost::container::vector<tnode> children;

    GLfloat x; //x coordinate of node 
    GLfloat y; //y coordinate of node
};

你所拥有的不符合标准 (感谢@jonathanwakely确认)。 所以它是未定义的行为 ,即使它在一些流行的平台上编译。

boost容器库有一些标准的类库容器,它们支持这个,所以你原则上可以修改你的struct来使用其中一个:

#include <boost/container/vector.hpp>
struct tnode
{
    int data;
    boost::container::vector<tnode> children;
    GLfloat x; //x coordinate of node 
    GLfloat y; //y coordinate of node
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM