我有一个问题问你。假设我有一个向量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;
}


那么有人有想法吗?

非常感谢

最佳答案

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

为此,您可以看一下boost::container库。

Boost::container

关于c++ - vector C++的奇怪行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15904716/

10-10 22:42