• c++ 容器中元素计数


    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <functional>
    #include<set>

    using namespace std;

    //一元谓词
    bool isEven(int elementParam)
    {
      if (elementParam%2==0)
      {
        return true;
      }
      return false;
    }


    int main()
    {
      vector<int> vec1;
      for (int k=0;k<10;k++)
      {
        vec1.push_back(k);
      }

      vec1.push_back(4);
      vec1.push_back(4);

      for (vector<int>::iterator iter=vec1.begin();iter !=vec1.end();++iter)
      {
        cout << *iter << " ";
      }
      cout << endl;

      int num = count(vec1.begin(),vec1.end(),4);
      cout << "" << num << endl;

      //偶数的个数
      int num2 = count_if(vec1.begin(),vec1.end(),isEven);
      cout << "" << num2 << endl;

      //bind2nd:函数适配器
      //greater:函数对象 ,有两个参数,用于判断第一个参数是否大于第二个参数
      int num3 = count_if(vec1.begin(),vec1.end(),bind2nd(greater<int>(),6));
      cout << "大于4的数:"<<num3<< endl;

      int num4 = count_if(vec1.begin(),vec1.end(),bind2nd(modulus<int>(),2));
      cout << "偶数个数:" << num4 << endl;

      multiset<int> multiset1;
      for (int k=0;k<10;k++)
      {
        multiset1.insert(multiset1.begin(),k);
      }

      multiset1.insert(3);
      multiset1.insert(6);
      multiset1.insert(6);

      multiset<int>::iterator multiset_iter1;
      for (multiset_iter1 = multiset1.begin();multiset_iter1 !=multiset1.end();++multiset_iter1)
      {
        cout << *multiset_iter1 << " ";
      }
      cout << endl;

      int num5 = count(multiset1.begin(),multiset1.end(),3);
      cout << "count:" << num5 << endl;

      //效率高
      int num6 = multiset1.count(6);
      cout << "count:" << num6 << endl;

      system("pause");
      return 0;
    }

    ===================================================

    0 1 2 3 4 5 6 7 8 9 4 4
    3
    7
    大于4的数:3
    偶数个数:5
    0 1 2 3 3 4 5 6 6 6 7 8 9
    count:2
    count:3
    请按任意键继续. . .

  • 相关阅读:
    再谈Asp.Net页面生命周期
    多线程、方便扩展的Windows服务程序框架
    用NuGet.Server管好自家的包包
    github for Windows
    MongoVUE 15天试用期解决办法
    NET插件系统——提升系统搜索插件和启动速度的思考
    Visual Studio Ultimate 2012 RC 安装手记
    自动完成菜单
    HBase
    WCF消息可靠性于有序传递
  • 原文地址:https://www.cnblogs.com/herd/p/10999996.html
Copyright © 2020-2023  润新知