0

我有一个问题问你。假设我有一个 AwesomeData 向量,而 AwesomeData 类包含一个 AwesomeData 向量。如果我尝试访问第一个向量内的向量,它将无法正常工作。据我所知,这并不清楚这里有一个更明确的例子:

struct AwesomeData
{
public:
    AwesomeData()
    : beautifulInt(3)
    {}

    int beautifulInt;
    vector<AwesomeData> someVector;
};

int main()
{
    vector<AwesomeData> tata;
    AwesomeData toto;

    toto.someVector.push_back(AwesomeData());
    toto.someVector.push_back(AwesomeData());
    toto.someVector.push_back(AwesomeData());

    tata.push_back(AwesomeData());
    tata.push_back(toto);
    tata.push_back(AwesomeData());


    // So, now tata should containt the data of someVector of toto (3 default    
    // AwesomeData). Instead of that, his capacity is equal to 3, but his
    // size = 0. So, what's wrong ?
    tata = tata[1].someVector;
}

但是,嘿,这还不是全部!我找到了解决方法,但我不知道它为什么有效。

struct AwesomeData
{
public:
    AwesomeData()
        : beautifulInt(3)
    {}

    int beautifulInt;
    vector<AwesomeData> someVector;
};

int main()
{
    vector<AwesomeData> tata;
    AwesomeData toto;

    toto.someVector.push_back(AwesomeData());
    toto.someVector.push_back(AwesomeData());
    toto.someVector.push_back(AwesomeData());

    tata.push_back(AwesomeData());
    tata.push_back(toto);
    tata.push_back(AwesomeData());


    // If we use a second vector to temporaly stock the vector of toto,
    // everything work as expected
    vector<AwesomeData> tempVector;

    tempVector = tata[1].someVector;
    tata = tempVector;
}

所以有人有想法吗?

非常感谢

4

1 回答 1

3

标准容器不允许您使用不完整的类型来实例化它们。在您AwesomeData尝试实例化 a 时,您的示例未完全定义std::vector<AwesomeData>

为此,您可以查看该boost::container库。

Boost::container

于 2013-04-09T14:34:26.530 回答