C++中bind1st和bind2nd什么时候会用到

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
/*
绑定器和函数对象operator()
1.C++ STL中绑定器
bind1st:operator()的第一个形参变量绑定成一个确定的值
bind2nd:operator()的第二个形参变量绑定成一个确定的值

2.C++11从Boost库引入了bind绑定器和function函数对象机制

3.lambda表达式 底层依赖函数对象的机制实现的

*/
template<typename Container>
void showContainer(Container& con)
{
	typename Container::iterator it = con.begin();
	for (;it != con.end();++it)
	{
		std::cout << *it << " ";
	}
	std::cout << std::endl;
}
int main()
{
	std::vector<int> vec;
	srand(time(nullptr));
	for (int i = 0;i < 20;++i)
	{
		vec.push_back(rand() % 100 + 1);
	}
	showContainer(vec);
	sort(vec.begin(), vec.end());//默认小到大排序
	showContainer(vec);
	//greater 二元函数对象
	sort(vec.begin(), vec.end(), std::greater<int>());//大到小排序
	showContainer(vec);
	/*
	把70按顺序插入到vec容器中,找到一个小于70的数字
	operator()(const T &val)
	greater  a>b
	less     a<b
	绑定器+二元函数对象=>一元函数对象
	bind1st: +bool operator()(70,const _Ty&  _Right)
	bind2nd: +less bool operator()(const _Ty& _Left,70)
	*/
	//auto it1= find_if(vec.begin(), vec.end(), std::bind1st(std::greater<int>(), 70));
	auto it1 = find_if(vec.begin(), vec.end(), std::bind2nd(std::less<int>(), 70));
	if (it1 != vec.end())
	{
		vec.insert(it1, 70);
	}
	showContainer(vec);	
}

输出信息

26 43 44 15 24 24 37 67 97 74 29 35 59 40 9 20 99 66 12 68
9 12 15 20 24 24 26 29 35 37 40 43 44 59 66 67 68 74 97 99
99 97 74 68 67 66 59 44 43 40 37 35 29 26 24 24 20 15 12 9
99 97 74 70 68 67 66 59 44 43 40 37 35 29 26 24 24 20 15 12 9
posted @ 2025-10-26 17:26  焦涛  阅读(0)  评论(0)    收藏  举报