C++ STL学习笔记

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;
}
输出结果为:

240
100
200
300
102
555
100
200
300
5
56
102
555
90
数组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;
}
输出结果为:

100
200
300

另外,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/







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值