1. remove()
2. remove_if()
注意:
1.并不是真正的删除,而是把后面的元素向前移动,覆盖被删除元素
2.返回新的逻辑终点
#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
using namespace std;
template <typename T>
void Print( const T& t )
{
for(typename T::const_iterator itr=t.begin(); itr!=t.end(); ++itr)
{
cout<<*itr<<' ';
}cout<<endl;
}
int main()
{
list<int> lst;
for(int i=1; i<=6; ++i)
{
lst.push_front(i);
lst.push_back(i);
}
Print(lst);
list<int>::iterator end;
end = remove( lst.begin(), lst.end(), 3 );
for(list<int>::const_iterator itr=lst.begin(); itr!=end; ++itr )
{
cout<<*itr<<' ';
}cout<<endl;
cout<<"erase total "<<distance(end, lst.end())<<" num 3"<<endl;
//真正删除
lst.erase(end, lst.end());
Print(lst);
vector<int> vec;
for( int i=2; i<=6; ++i )
{
vec.push_back(i);
}
for( int i=4; i<=9; ++i )
{
vec.push_back(i);
}
for( int i=1; i<=7; ++i )
{
vec.push_back(i);
}
Print(vec);
vec.erase(remove(vec.begin(), vec.end(), 5), vec.end());
Print(vec);
vec.erase(remove_if(vec.begin(), vec.end(),
bind2nd(less<int>(), 4)), vec.end());
Print(vec);
return 0;
}
本文通过示例代码介绍了C++标准模板库中remove与remove_if函数的功能及使用方法,演示了如何从list和vector容器中移除特定元素,并解释了这些函数的工作原理。
1980

被折叠的 条评论
为什么被折叠?



