关于 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 );
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;}
阅读全文
0 0
- 关于 STL 的 remove_if
- STL-remove_if()的用法
- 关于remove_if的错误用法
- stl中remove和remove_if的陷阱
- 关于remove_if
- STL中remove_if()/find_if()/replace_if()的使用方法(The usages of remove_if()/find_if()/replace_if() )
- stl list.remove_if使用
- STL remove和remove_if
- 关于std::remove_if
- STL 如何使用list::remove_if
- remove_if的误区
- remove_if的用法,浅谈
- remove_if的使用
- remove_if 的用法
- remove_if的使用
- stl内的remove_if函数和remove函数和list类的remove函数简单例子
- STL常用算法: remove,remove_if,remove_copy,remove_copy_if,remove系列算法和partition的区别...
- remove_if
- JAVA面向对象-异常
- 开发中的git分支管理
- [笔记分享] [Android] Android系统开发
- PKOJ 3070 矩阵快速幂问题
- Linux系统的运行模式简介
- 关于 STL 的 remove_if
- Android Activity
- C++ OOP
- 项目6_FSA鞋子定制项目3D扫描仪 设备接线调试总结
- python零碎知识(4)--语句
- AtCoder Grand Contest 019 C
- RSA算法证明-RSA算法证明参考资料
- sublime 常用快捷键
- java中的Properties类