泛型算法 = template + 迭代器 + 函数对象
特点一:泛型算法的参数接收的都是迭代器
特点二:泛型算法的参数还可以接收函数对象
sort,find,find_if,binary_search,for_each
绑定器+二元函数对象 = 一元函数对象
bind1st:把二元函数对象的operator(a,b)的第一个形参绑定起来
bind2nd:把二元函数对象的operator(a,b)的第二个形参绑定起来
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>//包含函数对象和绑定器
using namespace std;
int main()
{
int arr[] = { 13,56,94,78,42,12,36,98,75,11 };
vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0]));
for (int v : vec)
{
cout << v << " ";
}
cout << endl;
sort(vec.begin(), vec.end());
for (int v : vec)
{
cout << v << " ";
}
cout << endl;
if (binary_search(vec.begin(), vec.end(),21))
{
cout << "21存在 " << endl;
}
else
{
cout << "21不存在 " << endl;
}
auto it = find(vec.begin(), vec.end(), 21);
if (it != vec.end())
{
cout << "21存在 " << endl;
}
else
{
cout << "21不存在 " << endl;
}
//传入函数对象greater,改变容器元素排序时的比较方式
sort(vec.begin(), vec.end(),greater<int>());
for (int v : vec)
{
cout << v << " ";
}
cout << endl;
//把48插入到容器中去,find_if需要一元函数对象
auto it1 = find_if(vec.begin(), vec.end(),
/*bind1st(greater<int>(),48)*/
/*bind2st(less<int>(), 48)*/
[](int val)->bool {return val < 48; });
vec.insert(it1, 48);
for (int v : vec)
{
cout << v << " ";
}
cout << endl;
//for_each可以遍历容器的所有元素,可以自行添加合适的函数对象对容器的元素进行过滤
for_each(vec.begin(), vec.end(), [](int val)->void
{
if (val % 2 == 0)
{
cout << val << " ";
}
});
cout << endl;
}