STL remove函数

STL remove函数算法

STL 中的 remove() 函数用于从它的前两个正向迭代器参数指定的序列中移除和第三个参数相等的对象。基本上每个元素都是通过用它后面的元素覆盖它来实现移除的。它会返回一个指向新的最后一个元素之后的位置的迭代器。

STL remove函数详解

头文件

#include <algorithm>

语法

template<class ForwardIterator, class T> ForwardIterator remove( ForwardIterator first, ForwardIterator last, const T& value)

参数

参数 描述
first1 输入迭代器
last1 输入迭代器
value 要输入的元素

说明

它会返回一个指向新的最后一个元素之后的位置的迭代器。

案例

STL remove函数

使用 STL remove 函数删除元素

#include<iostream> #include<deque> #include<string> #include<algorithm> #include<iterator> using namespace std; int main() { std::cout << "嗨客网(www.haicoder.net)\n" << std::endl; deque<int> int_deque; for( int i = 1; i <=6 ; ++i) { int_deque.push_back(i); int_deque.push_front(i); } cout<<"pre:"; copy( int_deque.begin(), int_deque.end(), ostream_iterator<int>( cout ," ") ); cout<<endl; deque<int>::iterator new_end;//using for marking the new end of collenction logiclly new_end = remove( int_deque.begin(),int_deque.end(),3 ); cout<<"post:"; copy( int_deque.begin(), new_end, ostream_iterator<int>(cout," ")); cout<< endl; return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ remove.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

47_STL remove函数.png

我们使用了 remove 函数,实现了集合中删除元素。

STL remove函数总结

STL 中的 remove() 函数用于从它的前两个正向迭代器参数指定的序列中移除和第三个参数相等的对象。基本上每个元素都是通过用它后面的元素覆盖它来实现移除的。它会返回一个指向新的最后一个元素之后的位置的迭代器。