? ? ? ?
目錄
?算術仿函數
關系仿函數?
邏輯仿函數?
? ? ? ? C++ 標準庫中提供了一些內置的函數對象,也稱為仿函數,它們通常位于 <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 <iostream>
#include <functional>using namespace std;int main() {plus<int> m;//加法仿函數cout << m(10,20) << endl;minus<int> m1;//減法仿函數cout << m1(20, 10) << endl;multiplies<int> m2;//乘法仿函數cout << m2(20, 10) << endl;divides<int> m3;//除法仿函數cout << m3(20, 10) << endl;modulus<int> m4;//取模仿函數cout << m4(20, 8) << endl;negate<int> m5;//取反仿函數cout << m5(20) << endl;return 0;
}
?
關系仿函數?
功能描述:
- 實現關系對比
仿函數原型:
- 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> //小于等于
void test01()
{vector<int> v;v.push_back(10);v.push_back(30);v.push_back(50);v.push_back(40);v.push_back(20);for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {cout << *it << " ";}cout << endl;//自己實現仿函數//sort(v.begin(), v.end(), MyCompare());//STL內建仿函數 大于仿函數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;
}
?
邏輯仿函數?
功能描述:
- 實現邏輯運算
函數原型:
- template<class T> bool logical_and<T> //邏輯與
- template<class T> bool logical_or<T> //邏輯或
- template<class T> bool logical_not<T> //邏輯非
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;
}
?
?寫在最后:以上就是本篇文章的內容了,感謝你的閱讀。如果感到有所收獲的話可以給博主點一個贊哦。如果文章內容有遺漏或者錯誤的地方歡迎私信博主或者在評論區指出~??