简体   繁体   中英

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] . 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. As it is written now, you malloc space for the vector and set all the bytes occupied by the vector to zero. You never call the std::vector constructor for the allocated object, so you can't use it as a std::vector .

Make sure you have a good introductory C++ book from which to learn the language. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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