STL_00: bind1st与bind2nd的使用

STL_00: bind1st与bind2nd的使用

今天是看代码的过程中发现bind1st和bind2nd这两个函数,不太理解什么意思,经过查找资料理解了什么意思。记录下:

0x00 作用

bind1st(const Operation& op, const T& x)
bind2nd(const Operation& op, const T& x)

bind1stbind2nd函数用于将一个二元函数对象(binary functor,bf)转换成一元函数对象(unary functor,uf)。为了达到这个目的,它们需要两个参数:要转换的bf一个值(value)

bind1st 把 value作为 bf 的左值,bind2nd 把 value 作为 bf 的右值

简单来说,当我们进行比较时我们需要写x > value, x < value, value是一个参数, 表示你程序里面的表达式要和value值去比较。上面这两个表达式对应的应该是bind2nd ,value作为进行二元操作的对象写在了右边。
同理如果使用bind1st则对应的表达式是 value > x,value < x,value作为进行二元操作的对象写在了左边

0x01 使用实例

/*********************************************************************************************
    *  @Copyright (c) , All rights reserved.
    *  @file:       main.cpp
    *  @version:    ver 1.0
    *  @author:     zbb
    *  @brief:  
    *  @change:
    *  @email: 	binbin_erices@163.com
    *  Date             Version    Changed By      Changes 
    *  2020/3/8 0:25    1.0        zbb             create
**********************************************************************************************/
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>


int main()
{
	int a[] = { 1, 2, 4, 5, 6, 7, 8, 9 };
	int length = sizeof(a) / sizeof(*a);
	std::vector<int> arr(a, a+length);

	// 查找arr中元素数值大于5的个数
	int count = std::count_if(arr.begin(), arr.end(), std::bind1st(std::less<int>(), 5));
	std::cout << count << std::endl; //4
	// 查找arr中元素数值小于5的个数
	count = std::count_if(arr.begin(), arr.end(), std::bind2nd(std::less<int>(), 5));
	std::cout << count << std::endl; //3

    //删除arr中等于5的元素
	arr.erase(std::remove_if(arr.begin(), arr.end(), bind1st(std::equal_to<int>(), 5)), arr.end());
	for (auto item : arr)
		std::cout << item << " ";
	std::cout << "\n";
	//删除大于等于5的元素
	arr.erase(std::remove_if(arr.begin(), arr.end(),
		std::not1(std::bind2nd(std::less<int>(), 6))), arr.end());
	for (auto item : arr)
		std::cout << item << " ";
    getchar();
	return 0;
}
输出为:
4
3
1 2 4 6 7 8 9
1 2 4

注意: not1是构造一个与谓词结果相反的一元函数对象, not2是构造一个与谓词结果相反的二元函数对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Erice_s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值