簡體   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