C ++从对列表中删除 [英] C++ Erasing from list of pairs
问题描述
很简单:我有下面的代码和方法 erase
不工作。我没有看到任何问题,因为如果我去 http://www.cplusplus。 com / reference / list / list / erase / ,语法是:迭代器擦除(迭代器位置);
list< pair< string,int>> l0 {{name1,20},{name2,30},{name3,40}};
for(auto& it:l0)
l0。擦除(it);
可能有一个问题,有一个 编辑:问题是代码不可编译。 范围用于通过容器遍历访问容器中的 因此在 这就是说,πάνταῥῖῖ指出, of 迭代器,指向由该函数移除的元素的指针和引用被无效。 解决方法 你不能使用range-for,而是使用传统的 Very simple: I have the following code and the method May there be a problem that there is a 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 This being said, as πάνταῥεῖ pointed out when he initially closed this as a duplicate of
Keeping 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: Iterators, pointers and references referring to elements removed by the function are invalidated.
All other iterators, pointers and references keep their validity. Workaround You shall not use the range-for, but the traditional 这篇关于C ++从对列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!列表$ c $基本数据类型的
对< string,int>
而不是列表
b
$ b
元素,而不是元素的迭代器。
中为(auto& it:l0)
, c $ c>不是一个对的迭代器,但
a引用一个对。这就是为什么你的代码不能编译
在erase()后保留有效的vector :: iterator ,即使你的代码
编译它不会工作,因为迭代器无效后擦除:
所有其他迭代器,指针和引用保持其有效性。
for
,并使用 erase()
:
for(auto it = l0.begin(); it! l0.end();)
it = l0.erase(it); //避免增加无效的迭代器
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 );
list
of pair<string,int>
and not a list
of a basic data types?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
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