C++算法count()和count_if()

泛型算法名稱

count()     計數

作用

在容器中搜索需要計數的值,計算有多少個該值,返回整形

參數

容器開頭, 容器結尾,需要計數的值

 

泛型算法名稱

count_if()     有條件計數

作用

在容器中搜索滿足條件的值,計算有多少個該值,返回整形

參數

容器開頭, 容器結尾,仿函數(條件)

 

//創建容器

vector<int> CreateVector()

{

    vector<int> VeInt;

    VeInt.push_back(1);

    VeInt.push_back(2);

    VeInt.push_back(2);

    VeInt.push_back(3);

    VeInt.push_back(2);

    VeInt.push_back(4);

    VeInt.push_back(5);

    VeInt.push_back(5);

    VeInt.push_back(6);

    VeInt.push_back(1);

    return VeInt;

}

 

//輸出容器

void ShowVector(vector<int> VeInt)

{

    vector<int>::iterator showVeInt;

    for (showVeInt = VeInt.begin(); showVeInt != VeInt.end(); showVeInt++)

    {

         cout << *showVeInt << " ";

    }

    cout << endl;

}

 

//計數

int my_count(vector<int> intvector, int value)

{

    return count(intvector.begin(), intvector.end(), value);

}

 

//有條件計數(仿函數)

int my_count_if_if(int intvecto)

{

    return intvecto > 2;

}

 

//有條件計數

int my_count_if(vector<int> intvector, int value)

{

    return count_if(intvector.begin(), intvector.end(), my_count_if_if);

}

 

//主方法

void main()

{

    vector<int> VeInt = CreateVector();

    cout << "VeInt" << "\t";

    ShowVector(VeInt);

    int sum = my_count(VeInt,2);

    cout << "\n" << "該容器中存在“2”有:" << sum << "個。" << endl;

    int sum1 = my_count_if(VeInt, 2);

    cout << "\n" << "該容器中存在大於“2”的有:" << sum1 << "個。" << endl;

}

 

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