关于 STL 的 remove_if

来源:互联网 发布:国家外汇管理局 知乎 编辑:程序博客网 时间:2024/05/23 15:39

函数原型:

以下转自:http://blog.sina.com.cn/s/blog_68c02fb90100xhoi.html 侵删
#include <algorithm>
forward_iterator remove_if( forward_iterator start, forward_iterator end, Predicate p );

函数remove_if()移除序列[start, end)中所有应用于谓词p返回true的元素.

此函数返回一个指向被修剪的序列的最后一个元素迭代器.

记住, remove_if()并不会实际移除序列[start, end)中的元素; 如果在一个容器上应用remove_if(), 容器的长度并不会改变(remove_if()不可能仅通过迭代器改变容器的属性), 所有的元素都还在容器里面. 实际做法是, remove_if()将所有应该移除的元素都移动到了容器尾部并返回一个分界的迭代器. 移除的所有元素仍然可以通过返回的迭代器访问到. 为了实际移除元素, 你必须对容器自行调用erase()以擦除需要移除的元素. 这也是erase-remove idiom名称的由来:

container.erase(remove_if(container.begin(), container.end(), pred), container.end());

remove_if()类似于partition(), 但有两点不同: 1) 它们使用的谓词条件刚好相反. 2) remove_if只强调前面部分(第二部分不再需要了)

remove_if()以线性时间(linear time)运行.

remove_if()不能用于关联容器如set<>或map<>.


测试代码:


#include <iostream>#include <vector>#include <algorithm>#include "print.h"   // 打印元素using namespace std;int main(){vector<int> coll;for (int i = 1; i <= 9; ++i)coll.push_back(i);PRINT_ELEMENTS(coll);    // 打印元素vector<int>::iterator pos;pos = remove_if(coll.begin(),coll.end(),bind2nd(less<int>(),7));    coll.erase(pos,coll.end());PRINT_ELEMENTS(coll);cout << endl;return 0;}

运行结果:


1 2 3 4 5 6 7 8 9
7 8 9
编译结果如图。

print.h如下:
#include <iostream>template <typename T>inline void PRINT_ELEMENTS(const T& coll, const char* opt = ""){typename T::const_iterator pos;std::cout << opt;for (pos = coll.begin(); pos != coll.end(); ++pos){std::cout << *pos << " ";}std:cout << std::endl;}