1. 程式人生 > 其它 >C++提高程式設計 4 STL -謂詞

C++提高程式設計 4 STL -謂詞

4.2 謂詞

4.2.1 謂詞概念

概念:

返回bool型別的仿函式稱為謂詞(Pred)

返回operator()接受一個引數,那麼叫做一元謂詞

返回operator()接受兩個引數,那麼叫做兩元謂詞

4.2.2 一元謂詞

#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>

//仿函式  返回值型別是bool資料型別,稱為謂詞
//一元謂詞

class GreaterFive
{
public:
    bool operator()(int val)
    {
        
return val > 5; } }; void test1() { vector<int>v; for (int i = 0; i < 10; i++) { v.push_back(i); } //查詢容器中有沒有大於5的數字 //GreaterFive() 匿名物件 vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive()); if (it == v.end()) { cout
<< "未找到" << endl; } else { cout << "找到了" << endl; //不用再用for迴圈遍歷了 因為此時的it已經是大於5的數字了 直接輸出*it即可 //for (vector<int>::iterator it = v.begin(); it != v.end(); it++) //{ // cout << *it << endl; //}
cout << *it << endl; } } int main() { test1(); system("pause"); return 0; }

4.2.2 二元謂詞

#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>

//二元謂詞
class myCompare
{
public:
    bool operator()(int val1, int val2)
    {
        return val1 > val2;
    }
};

void test1()
{
    vector<int>v;
    v.push_back(10);
    v.push_back(40);
    v.push_back(20);
    v.push_back(30);
    v.push_back(50);

    sort(v.begin(), v.end());
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << "  ";            // 10 20 30 40 50
    }
    cout << endl;

    //使用函式物件  改變演算法策略,變為排序規則為從大到小
    sort(v.begin(), v.end(), myCompare());

    cout << "------------------" << endl;
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << "  ";            // 50 40 30 20 10
    }
    cout << endl;
}

int main()
{
    test1();

    system("pause");
    return 0;
}