简体   繁体   English

矢量迭代器不兼容

[英]vector iterators incompatible

I have some class where I want to use a large amount of vectors. 我有一些课我想要使用大量的向量。

class Bar {
    Bar ();
    std::vector<Foo> * _grid;
    void someFunction ();
}

Bar::Bar () {
    _grid = (std::vector<Foo> *)malloc(_gridSize * sizeof(std::vector<Foo>);
    memset(_grid, 0, _gridSize * sizeof(std::vector<Foo>);
}

void Bar::someFunction () {
    int index = 0;
    std::vector<Foo> someVariable = _grid[index];
}

However, as soon as I call someFunction() , I get a vector iterators incompatible error message as soon as there is some content in _grid[index] . 但是,只要我调用someFunction()_grid[index]有一些内容,我就会得到一个vector iterators incompatible错误消息。 If the vector is empty, it works. 如果向量为空,则可以。

I've read about the error message being produced by invalidated iterators, however, since I don't change anything on the vectors at this point, I don't get what is wrong here. 我已经读过由无效的迭代器生成的错误消息,但是,因为此时我没有对向量进行任何更改,所以我不会在这里得到什么错误。

You almost certainly don't want to dynamically allocate the vector; 你几乎肯定不想动态分配向量; just include it as a member of the class: 只需将其作为班级成员包括在内:

class Bar { 
    std::vector<Foo> _grid;
};

If you really want to dynamically allocate the vector, you want to use new , which constructs the vector. 如果你真的想动态分配向量,你想使用new来构造向量。 As it is written now, you malloc space for the vector and set all the bytes occupied by the vector to zero. 正如现在所写的那样,你可以为vector提供malloc空间,并将向量占用的所有字节设置为零。 You never call the std::vector constructor for the allocated object, so you can't use it as a std::vector . 你永远不会为分配的对象调用std::vector构造函数,因此你不能将它用作std::vector

Make sure you have a good introductory C++ book from which to learn the language. 确保你有一本很好的入门C ++书籍来学习这门语言。 If you don't understand the C++ memory model and object model, there is now way you'll be able to write correct C++ code. 如果您不了解C ++内存模型和对象模型,那么现在您可以编写正确的C ++代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM