C++——list中erase和remove的区别

时间:2021-05-26 20:08:05

1.之前在做相关的操作的时候,涉及到清除list相关的元素,因此会用到erase和remove,那么二者有什么区别呢?

从官方文档中,我们可以获取以下信息

erase :

说明:Removes from the list container either a single element (position) or a range of elements ([first,last)).This effectively reduces the container size 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 container end 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 size by the number of elements removed.

返回值:空

erase是以迭代器为基本单位,清除元素,改变size的值;remove是以value相等为标准,也改变size的值。

2.在清空list中,我们该用什么操作

     //调用析构函数,清掉了list的内存
for (list<CUnit *>::iterator it = listStr.begin(); it != listStr.end(); )
{
delete *it;
listStr.erase(it++);
//listStr.remove(*it++);
}
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元素的后一个元素的迭代器)。

于是我们有了以下清除方法:

 #include"Allinclude.h"

 int main()
{ cout<<endl<<"map:"<<endl;
map<char, int> mymap;
// insert some values:
mymap['a'] = ;
mymap['b'] = ;
mymap['c'] = ;
mymap['d'] = ;
mymap['e'] = ;
mymap['f'] = ;
for (map<char, int>::iterator it = mymap.begin(); it != mymap.end();)
{
#if 1
if (it->second == )
{
//For the key - based version(2), the function returns the number of elements erased.
mymap.erase(it++);
}
else
{
it++;
}
#endif
//mymap.erase(it++);
}
for (map<char, int>::iterator it = mymap.begin(); it != mymap.end();it++)
{
cout << it->second << " , ";
} cout<<endl<<"vector:"<<endl; vector<int> myvector; // set some values (from 1 to 10)
for (int i = ; i <= ; i++)
myvector.push_back(i);
for (vector<int>::iterator it = myvector.begin(); it != myvector.end();)
{
#if 0
if (*it == )
{
myvector.erase(it++);
//等同于it=myvector.erase(it);因为返回值是下一个值的迭代器
}
else
{
it++;
}
#endif
myvector.erase(it);
} // set some values (from 1 to 10)
for (int i = ; i < myvector.size(); i++)
{
cout << myvector[i] << " , ";
} cout<<endl<<"list:"<<endl;
list<int> mylist; // set some values:
for (int i = ; i < ; ++i)
mylist.push_back(i * );
for (list<int>::iterator it = mylist.begin(); it != mylist.end();)
{
#if 1
if (*it == )
{
mylist.erase(it++);
//等同于it=myvector.erase(it);因为返回值是下一个值的迭代器
//it = mylist.erase(it);
}
else
{
it++;
}
#endif
//mylist.erase(it++);
} // set some values (from 1 to 10)
for (list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
{
cout << *it << " , ";
} system("pause");
return ;
}

其实我建议还是用

it = mylist.erase(it)

代码更加清晰一点。

其实最好还是用erase(begin(),end());除非要自己清除一些成员内存。

参考文献:

https://blog.csdn.net/liuzhi67/article/details/50950843