【问题标题】:mingw g++ vector<T>::insert bugmingw g++ vector<T>::insert 错误
【发布时间】:2010-12-19 14:04:30
【问题描述】:
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

【问题讨论】:

    标签: c++ stl vector iterator


    【解决方案1】:

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

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

    insert 的重载会为插入的元素返回一个新的迭代器,因此您可以替换它:

    nums.insert(it, 100500);
    

    用这个:

    it = nums.insert(it, 100500);
    

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

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

    【讨论】:

    • 最好不要将 C++ 标准库称为“STL”,部分原因是出于上述原因,主要是因为这不是它的名称。
    • @Tomalak:使用名称“STL”来指代源自 Alexander Stepanov 设计的原始 STL 库的 C++ 标准库的组件是一种常见且公认的做法。这包括 C++ 标准库的容器、迭代器、算法和函子库组件。
    • 我很清楚这很常见,但我对“接受”提出异议。我和其他许多人正试图清除滥用它的瘟疫!
    • @Tomalak:你和“许多其他人”只是迂腐和讨厌。这就像试图争辩说“const 引用”这个短语是不正确的,因为没有 const 限定的引用这样的东西。今天使用术语 STL 并没有混淆,因为每个人都指 C++ 标准库组件。没有人再使用原始的 SGI 库了:它是古老的历史。 Herb、Andrei 和 Scott 等受人尊敬的作者和 C++ 专家在更广泛的意义上使用术语 STL。这里有 2,100 个标记为 [stl] 的问题;如果其中五个是关于 SGI STL 的,我会感到惊讶。
    • @Tomalak: "Effective STL" 只处理 STL(来自原始 SGI STL 的标准库部分),而不是整个标准库,所以它不是用词不当。 (据我对 Scott 的了解,如果他把这个术语弄错了,我会感到惊讶。)
    【解决方案2】:

    这不是错误。在得出软件错误的结论之前,您未能正确阅读std::vector 文档;事实上,向量插入会使所有迭代器失效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      相关资源
      最近更新 更多