内建函數對象
概念:STL中内建一些函數對象
分類:
算術仿函數
關系仿函數
邏輯仿函數
需要引入頭檔案 #include < functional>
1.算術仿函數
有加減乘除,取模,取反(英文:plus,minus,multiplies,divides,modulus,negate)
模闆
template(class T) T negated < T> //(加)
其中隻有取反為一進制運算,其他為二進制運算
例如取反調用:
negate<int> n; //一進制參數隻有一個,二進制參數也隻有一個
cout<<n(10)<<endl; //輸出-10
例如加法調用:
plus<int> n; //二進制參數也隻有一個
cout<<n(10,20)<<endl; //輸出3
2.關系仿函數
模闆:
template< class T>bool equal_to< T > //等于
template< class T>bool not equal_to< T > //不等于
template< class T>bool greater< T > //大于 最常見
template< class T>bool greater_equal< T > //大于等于
template< class T>bool less< T > //小于
template< class T>bool less_equal< T > //小于等于
例子,内建函數放入sort中:
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <functional>
void test()
{
vector<int> v;
v.push_back(10);
v.push_back(15);
v.push_back(30);
v.push_back(40);
for(vector<int>::iterator it = v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
//使sort按降序來排
sort(v.begin(),v.end(),greater<int>()); //放入内建函數大于
for(vector<int>::iterator it = v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
int main()
{
test();
system("pause");
return 0;
}
運作結果:

3.邏輯仿函數
template< class T>bool logical_and < T> //邏輯與
template< class T>bool logical_or < T> //邏輯或
template< class T>bool logical_not < T> //邏輯非
搬運算法:
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <functional>
void test()
{
vector<bool> v; //布爾類型的容器
v.push_back(true);
v.push_back(true);
v.push_back(false);
v.push_back(false);
for(vector<bool>::iterator it = v.begin();it!=v.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
vector<bool> v2;
v2.resize(v.size()); //先開辟空間
transform(v.begin(),v.end(),v2.begin(),logical_not<bool>()); //利用搬運算法,搬運前首先要開辟容量
for(vector<bool>::iterator it = v2.begin();it!=v2.end();it++)
{
cout<<*it<<" ";
}
}
int main()
{
test();
system("pause");
return 0;
}