繁体   English   中英

mingw g ++矢量图 <T> ::插入错误

[英]mingw g++ vector<T>::insert bug

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;

退货

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

我什么都不懂。 救命!

mingw g ++ 4.5.0 win32

当您将新元素插入到vector ,插入位置之后的所有元素迭代器都将无效,并且如果发生重新分配,则容器中的所有迭代器都将无效。 只要v.capacity() - v.size()小于您要插入的元素数量,就会发生重新分配。

当迭代器无效时,意味着不能再使用该迭代器。 无效。

insert这种重载insert新的迭代器返回到插入的元素,因此您可以替换为:

nums.insert(it, 100500);

有了这个:

it = nums.insert(it, 100500);

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

请注意,SGI STL文档不是C ++标准库的正式文档,并且存在一些细微的差异,但是通常这些差异并不是特别重要; 需要注意的一件事是,SGI STL的某些部分未包含在C ++标准库中,而C ++标准库的某些部分则未包含在SGI STL中。

这不是错误。 您无法正确阅读std::vector文档,然后得出软件错误的结论。 实际上,向量插入会使所有迭代器无效。

暂无
暂无

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

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