问题描述
很简单:我有下面的代码和方法 erase
不工作。我没有看到任何问题,因为如果我去,语法是:迭代器擦除(迭代器位置);
list< pair< string,int>> l0 {{name1,20},{name2,30},{name3,40}};
for(auto& it:l0)
l0。擦除(it);
可能有一个问题,有一个 编辑:问题是代码不可编译。 用于通过容器遍历访问容器中的 因此在 这就是说,指出, of 解决方法 你不能使用range-for,而是使用传统的列表$ c $基本数据类型的
:对< string,int>
而不是列表
b
$ b
元素,而不是元素的迭代器。
中为(auto& it:l0)
, c $ c>不是一个对的迭代器,但
a引用一个对。这就是为什么你的代码不能编译
,即使你的代码
编译它不会工作,因为迭代器无效后擦除:
for
,并使用 erase()
for(auto it = l0.begin(); it! l0.end();)
it = l0.erase(it); //避免增加无效的迭代器
Very simple: I have the following code and the method erase
is not working. I do not see any problem there because if I go to http://www.cplusplus.com/reference/list/list/erase/ , syntax is: iterator erase (iterator position);
list<pair<string,int>> l0 { { "name1", 20 }, { "name2", 30 }, { "name3", 40 } };
for( auto &it : l0 )
l0 . erase( it );
May there be a problem that there is a list
of pair<string,int>
and not a list
of a basic data types?
EDIT: The problem is that the code is not compilable.
The range-for iterates through a container by giving you access to the elements in the container, and not an iterator to an element.
So in for( auto &it : l0 )
, it
isn't an iterator to a pair but a reference to a pair. This is why your code doesn't compile
This being said, as πάνταῥεῖ pointed out when he initially closed this as a duplicate ofKeeping a valid vector::iterator after erase(), even if your code would compile it wouldn't work because of the invalidation of the iterator following the erase:
Workaround
You shall not use the range-for, but the traditional for
, and iterating using the return value of erase()
:
for (auto it=l0.begin(); it!=l0.end(); )
it = l0.erase(it); // to avoid incrementing an invalidated iterator
这篇关于C ++从对列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!