修改列表后,std :: list <T> :: end()的值是否会发生变化?

Fil*_*ipp 8 c++ iterator stl list

我试图利用这样一个事实,即插入和删除之后列表的迭代器仍然有效(除了刚刚删除的迭代器之外).这也是如此std::list<T>::end();

假设我尝试以下方法:

typedef std::list<int> list_int;

list_int myList;
list_int::iterator iter = myList.end();

myList.push_back(1);
myList.push_back(2);
myList.push_back(3);

if(iter == myList.end()) {
    /* do things here */
} else {
    /* do different things here */
    /* I don't expect this branch to ever execute */
}
Run Code Online (Sandbox Code Playgroud)

This is important because elsewhere I might store a collection of iterators into this list, and I would test for validity by comparing against myList.end(). It's important that invalid iterators remain so even after insertions and removals.

AnT*_*AnT 17

std::lists end迭代器的值在列表的生命周期内永远不会改变.它始终有效,始终相同,并始终对应于列表中虚构的"过去结束"元素.这意味着some_list.end()在列表生命周期中任何一点记忆的值将始终some_list.end()与其生命周期中任何其他点的值相同.

语言规范没有明确说明.但是,列表上没有有效操作会使结束迭代器无效或将其值与其他位置相关联.

在您的示例中,第二个分支if将永远不会执行.

如果我没有错过什么,同样是真实的std::map,并std::set为好.