mingw g ++ vector <T> ::插入bug

puc*_*chu 0 c++ iterator stl vector

vector<int> nums;
nums.push_back(0);
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);

vector<int>::iterator it = nums.begin();
it++;

cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
    cout << (*jt) << endl;
}
cout << endl;

nums.insert(it, 100500);
cout << ">> insert(it, 100500)" << endl << endl;

cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
    cout << (*jt) << endl;
}
cout << endl;

it++;
cout << ">> it++" << endl << endl;

cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
    cout << (*jt) << endl;
}
cout << endl;

nums.insert(it, 100800);
cout << ">> insert(it, 100800)" << endl << endl;

cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
    cout << (*jt) << endl;
}
cout << endl;

it++;
cout << ">> it++" << endl << endl;

cout << "it points to " << *(it) << endl;
for(vector<int>::iterator jt = nums.begin(); jt != nums.end(); jt++) {
    cout << (*jt) << endl;
}
cout << endl;
Run Code Online (Sandbox Code Playgroud)

回报

it points to 1
0
1
2
3

>> insert(it, 100500)

it points to 1
0
100500
1
2
3

>> it++

it points to 2
0
100500
1
2
3

>> insert(it, 100800)

it points to 100800
134352185
0
100500
1
2
3

>> it++

it points to 2
134352185
0
100500
1
2
3
Run Code Online (Sandbox Code Playgroud)

我什么都不懂.救命!

mingw g ++ 4.5.0 win32

Jam*_*lis 6

当您将新元素插入a时vector,插入位置后元素的任何迭代器都将失效,并且如果发生重新分配,则所有进入容器的迭代器都将失效.每次重新分配都会v.capacity() - v.size()小于您尝试插入的元素数.

当迭代器失效时,意味着不能再使用迭代器.它无效.

这个重载insert返回插入元素的新迭代器,所以你可以替换它:

nums.insert(it, 100500);
Run Code Online (Sandbox Code Playgroud)

有了这个:

it = nums.insert(it, 100500);
Run Code Online (Sandbox Code Playgroud)

迭代器失效的规则对于每个容器都是不同的,您必须小心理解它们.STL的最佳参考之一是SGI STL文档.迭代器失效规则通常在每个容器文档页面的脚注中列出.

请注意,SGI STL文档不是C++标准库的官方文档,并且存在一些细微差别,但通常这些差异并不是特别重要; 需要注意的一点是,SGI STL的某些部分未包含在C++标准库中,并且C++标准库的某些部分不属于SGI STL.