43泛型算法和绑定器
泛型算法和绑定器
泛型算法是STL库里面定义的一些算法,这些算法可以用一个接口操作各种数据类型,因此称为泛型算法。
#include<algorithm>
- 泛型算法接受的都是迭代器,这是为了统一形式
 - 同时可以额外接受函数对象,更改泛型算法的功能
 

绑定器
当需要一个一元函数对象,但需要使用一个二元函数对象,其中一个函数型参是固定值,那么就用到了绑定器。
绑定器+二元函数对象 可转换为一元函数对象。
bind1st:把二元函数对象operator()的第一个参数与定值绑定bind2nd:把二元函数对象operator()的第二个参数与定值绑定lambda表达式就是创建临时的函数对象.
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
	int arr[] = { 12, 4, 78, 9, 21, 43, 56, 53, 42, 29 };
	vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0]));
	sort(vec.begin(), vec.end(), greater<int>());
	for (int v : vec)
	{
		cout << v << " ";
	}
	cout << endl;
	// 把48插入到第一个小于48的数字前面
	// greater a > b
	auto it2 = find_if(vec.begin(), vec.end(),
		//bind1st(greater<int>(), 48)); // 每次从迭代器指示范围进行 48 > x的比较
		//bind2nd(less<int>(), 48)); // 每次进行 x < 48的比较
		[](int val) -> bool { return val < 48; });
	vec.insert(it2, 48);
	for (int v : vec)
	{
		cout << v << " ";
	}
	return 0;
}

                
            
        
浙公网安备 33010602011771号