How to declare a structure vector inside the same structure?

I am trying to create a structure that includes a vector with a type that is the same structure. However, when I build, errors indicating that I am missing ';' before '>'. I'm not sure that the compiler even recognizes that the vector as a thing: / and I already included it in my code. Here is what I still have:

#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!

+4
source share
2 answers

Your code causes undefined behavior, since standard containers like vector cannot contain incomplete types, and tnode is an incomplete type in the structure definition. According to the C ++ 11 standard, 17.6.4.8p2:

effects are undefined in the following cases: [...] if the incomplete type (3.9) is used as a template argument when creating an instance of a template component, unless this is specifically permitted for this component.

The Boost.Container library provides alternative containers (including vector ) that may contain incomplete types. Recursive data types, such as the one you want, are provided as a use case.

The following will work with Boost.Container:

 #include <boost/container/vector.hpp> struct tnode { int data; //tnode is an incomplete type here, but that allowed with Boost.Container boost::container::vector<tnode> children; GLfloat x; //x coordinate of node GLfloat y; //y coordinate of node }; 
+6
source

You have a substandard (thanks @jonathanwakely for confirming this). Thus, this behavior is undefined, even if it compiles on some popular platforms.

The container extension library contains several standard libraries that support this, so you can basically change your structure to use it from them:

 #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 }; 
+3
source

Source: https://habr.com/ru/post/1488332/


All Articles