Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

struct

vector

I am trying to create a struct that includes a vector with type being that same struct. However, when I build, errors that indicate I am missing a ';' before '>' appear. I am not sure if the compiler is even recognizing that the vector as a thing :/ and I have already included in my code. Here is what I have so far:

#include <vector>

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

Any help would be greatly appreciated!!

like image 673
red Avatar asked Jan 13 '23 01:01

red


2 Answers

Your code is invoking undefined behavior because standard containers such as vector cannot contain incomplete types, and tnode is an incomplete type within the struct definition. According to the C++11 standard, 17.6.4.8p2:

the effects are undefined in the following cases: [...] if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

The Boost.Container library provides alternative containers (including vector) which can contain incomplete types. Recursive data types such as the one you want are given as a use case of this.

The following would work with 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
};
like image 122
interjay Avatar answered Jan 26 '23 04:01

interjay


What you have is not standards compliant (thanks to @jonathanwakely for confirming that). So it is undefined behaviour, even if it compiles on some popular platforms.

The boost container library has some standard library-like containers that do support this, so you could in principle modify your struct to use one of these:

#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
};
like image 26
juanchopanza Avatar answered Jan 26 '23 06:01

juanchopanza