1.之前在做相关的操作的时候,涉及到清除list相关的元素,因此会用到erase和remove,那么二者有什么区别呢?
从官方文档中,我们可以获取以下信息
erase :
说明:Removes from the container either a single element (position) or a range of elements ([first,last)).This effectively reduces the container by the number of elements removed, which are destroyed.以iterator为单元,对元素进行清除。
返回值:An iterator pointing to the element that followed the last element erased by the function call. This is the if the operation erased the last element in the sequence.
remove:
说明:Remove elements with specific value。Removes from the container all the elements that compare equal to val. This calls the destructor of these objects and reduces the container by the number of elements removed.
返回值:空
erase是以迭代器为基本单位,清除元素,改变size的值;remove是以value相等为标准,也改变size的值。
2.在清空list中,我们该用什么操作
1 //调用析构函数,清掉了list的内存2 for (list::iterator it = listStr.begin(); it != listStr.end(); )3 {4 delete *it;5 listStr.erase(it++);6 //listStr.remove(*it++);7 }8 listStr.clear();
此处不要用remove,什么样的函数,就干什么样子的事情,别瞎用c++的函数。
3.另外一个问题,为什么erase(it++)?
从1中,我们可以看到erase的返回值是iterator。An iterator pointing to the element that followed the last element erased by the function call(指向erase元素的后一个元素的迭代器)。
于是我们有了以下清除方法:
1 #include"Allinclude.h" 2 3 int main() 4 { 5 6 cout<<<"map:"< mymap; 8 // insert some values: 9 mymap['a'] = 10;10 mymap['b'] = 20;11 mymap['c'] = 30;12 mymap['d'] = 40;13 mymap['e'] = 50;14 mymap['f'] = 60;15 for (map ::iterator it = mymap.begin(); it != mymap.end();)16 {17 #if 118 if (it->second == 10)19 {20 //For the key - based version(2), the function returns the number of elements erased.21 mymap.erase(it++);22 }23 else24 {25 it++;26 }27 #endif28 //mymap.erase(it++);29 }30 for (map ::iterator it = mymap.begin(); it != mymap.end();it++)31 {32 cout << it->second << " , ";33 }34 35 cout< <<"vector:"<