mardi 3 décembre 2019

What happens to the iterator if the underlaying container is changed? [duplicate]

This question already has an answer here:

What happens to an iterator if the container that it iterates over is changed?

Here is the code:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1,2,3};
    std::vector<int>::iterator it = v.begin();
    std::cout << *it << '\n';
    it++;
    std::cout << *it << '\n';
    v.emplace_back(4);
    it++;
    std::cout << *it << '\n';
    it++;
    std::cout << *it << '\n';

    return 0;
}

output:

1
2
12230672 // every time you run you get a different value.
0

Aucun commentaire:

Enregistrer un commentaire