lundi 23 octobre 2017

Why iterator of container is invalidated when this container is also an element of a container?

int main() {
std::vector<std::vector<int>> v;
v.push_back({1,2,3,4});

auto it = v.at(0).begin();
int size = v.at(0).size();
std::cout<<size<<std::endl;
for (int i = 0; i < size; ++it)
{
    v.push_back({5,6,7,8});
//std::cout<<*it<<std::endl;
}

return 0;
}

The iterator is broken when I push some elements into the outer container. what should I do if I really want to iterate the container element inside of outer container and at the same time keep pushing back some new elements ? Many thanks!

Aucun commentaire:

Enregistrer un commentaire