【问题标题】:How Container end() iterator evolves when (e.g) Container size change [duplicate]当(例如)容器大小变化时,容器 end() 迭代器如何演变[重复]
【发布时间】:2017-06-16 05:38:18
【问题描述】:

我想知道为什么下面的测试

end_iter_mem == intList.end()

返回真

coliru

当容器的元素数量增加时,容器的 end() “值”不应该发生变化吗?

#include <iostream>
#include <list>

using namespace std;

int main()
{
    list<int> intList = {1,2,3};

    auto end_iter_mem = intList.end();

    intList.push_back(4);

    cout << (end_iter_mem == intList.end()) << endl;

    return 0;
}

【问题讨论】:

标签: c++ stl iterator


【解决方案1】:

列表的迭代器在list::push_back 操作后不会失效,来自cppreference

没有迭代器或引用无效。

但这并不意味着所有容器都是如此。例如vectors the documentation says

如果新的 size() 大于 capacity() 则所有迭代器和引用(包括过去的迭代器)都将失效。否则只有过去的迭代器无效。


tl;dr 您必须查阅文档以了解迭代器是否失效以及哪些迭代器在容器修改后失效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    相关资源
    最近更新 更多