编程语言
首页 > 编程语言> > c++ 容器中元素计数

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
请按任意键继续. . .

 

 

标签:容器,begin,end,cout,int,multiset1,c++,计数,vec1
来源: https://www.cnblogs.com/herd/p/10999996.html