STL中的內建函數對象(一看就懂)

什麼是內建函數對象

答: STL提供的仿函數

STL內建了一些函數對象。分爲:算數類函數對象,關係運算類函數對象,邏輯運算 類仿函數。這些仿函數所產生的對象,用法和一般函數完全相同,當然我們還可以 產生無名的臨時對象來履行函數功能。使用內建函數對象,需要引入頭文件

6個算數類函數對象,除了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>// 取 反 仿 函 數 
6個關係運算類函數對象,每一種都是二元運算。 
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>// 小 於 等 於 
邏輯運算類運算函數,not爲一元運算,其餘爲二元運算。 
template<class T> bool logical_and<T>// 邏 輯 與 
template<class T> bool logical_or<T>// 邏 輯 或 
template<class T> bool logical_not<T>// 邏 輯 非

案例(加法仿函數)

// 加 法 仿 函 數 
void test02() 
{ 
	plus<int> p; 
	cout << p(10, 20) << endl;			//30
	cout<<plus<int>()(100,300)<<endl;	//300
}

案例二(使用內建函數對象 改變排序規則)

//使用內建函數對象 改變排序規則
void test04()
{
    vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    v.push_back(40);
    v.push_back(50);

    for_each(v.begin(),v.end(),[](int val){cout<<val<<" ";});
    cout<<endl;

    //使用內建函數對象 改變排序規則
    sort(v.begin(),v.end(), greater<int>() );
    
    for_each(v.begin(),v.end(),[](int val){cout<<val<<" ";});
    cout<<endl;
}

運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章