這裏有C++STL——全面總結詳細教程(附案例解析)(持續更新中)
內建函數對象
內建函數對象意義
概念:
-
STL內建了一些函數對象
分類:
-
算術仿函數
-
關係仿函數
-
邏輯仿函數
用法:
- 這些仿函數所產生的對象,用法和一般函數完全相同
- 使用內建函數對象,需要引入頭文件
#include<functional>
算術仿函數
功能描述:
-
實現四則運算
-
其中negate是一元運算,其他都是二元運算
仿函數原型:
template<class T> T plus<T>
//加法仿函數template<class T> T minus<T>
//減法仿函數template<class T> T multiplies<T>
//乘法仿函數template<class T> T divides<T>
//除法仿函數template<class T> T modulus<T>
//取模仿函數template<class T> T negate<T>
//取反仿函數
#include<functional>
#include<iostream>
using namespace std;
//negate
void test01(){
negate<int> n;
cout << n(50) << endl;
}
//plus
void test02(){
plus<int> p;
cout << p(10, 20) << endl;
}
int main() {
test01();
test02();
system("pause");
return 0;
}
總結:使用內建函數對象時,需要引入頭文件 #include <functional>
關係仿函數
功能描述:
-
實現關係對比
仿函數原型:
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>
//小於等於
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
class MyCompare {
public:
bool operator()(int v1,int v2) {
return v1 > v2;
}
};
void test01() {
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//sort(v.begin(), v.end(), MyCompare());
sort(v.begin(), v.end(), greater<int>());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
我們用自己內置的大於仿函數原型。
總結:關係仿函數中最常用的就是greater<>大於。
邏輯仿函數
功能描述:
-
實現邏輯運算
函數原型:
template<class T> bool logical_and<T>
//邏輯與template<class T> bool logical_or<T>
//邏輯或template<class T> bool logical_not<T>
//邏輯非
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
void test01() {
vector<bool> v;
v.push_back(true);
v.push_back(false);
v.push_back(true);
v.push_back(false);
for (vector<bool>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//邏輯非 將v容器搬運到v2中,並執行邏輯非運算
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 << " ";
}
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
總結:邏輯仿函數實際應用較少,瞭解即可