C++ STL学习笔记

来源:互联网 发布:国企混日子 知乎 编辑:程序博客网 时间:2024/06/05 16:21

remove_if使用方法:

int a[] = { 1, 2, 240, 4, 5, 6, 100, 200, 300, 5, 56, 102, 555, 90};vector<int> arr(a, a + 14);std::remove_if(arr.begin(), arr.end(), std::bind2nd(std::less<int>(), 100));for (int i = 0; i < arr.size(); ++i){cout << arr[i] << endl;}
输出结果为:

24010020030010255510020030055610255590
数组arr是有序数组,remove_if()会复制所有不满足条件(less函数对象返回值为假)的元素到原数组的起始位置并覆盖之前的元素。返回不满足条件的元素与满足条件的元素分隔线处的迭代器。

因此,remove_if()配合erase使用能达到删除指定元素的效果。

int a[] = { 1, 2, 3, 4, 5, 6, 100, 200, 300};vector<int> arr(a, a + 9);arr.erase(std::remove_if(arr.begin(), arr.end(), std::bind2nd(std::less<int>(), 100)), arr.end());for (int i = 0; i < arr.size(); ++i){    cout << arr[i] << endl;}
输出结果为:

100200300

另外,bind2nd(const Operation& op, const T& x)中的第一个参数op是一个binary function object。binary function object op接受两个参数,bind2nd()绑定op的第二个参数为x。功能相似的函数还有bind1st。相关的介绍详见:

http://www.cplusplus.com/reference/functional/binary_function/







原创粉丝点击