STL算法系列---count()
STL中有很多常用的算法,可以方便我们使用容器。
转载:http://blog.csdn.net/hyg0811/article/details/10602283
一.count函数
algorithm头文件定义了一个count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现次数的统计结果。
编写程序读取一系列int型数据,并将它们存储到vector对象中,然后统计某个指定的值出现了多少次。
核心代码:
cout<<count(ivec.begin() , ivec.end() , searchValue)
具体实现:
1 //读取一系列int数据,并将它们存储到vector对象中, 2 //然后使用algorithm头文件中定义的名为count的函数, 3 //统计某个指定的值出现了多少次 4 #include<iostream> 5 #include<vector> 6 #include<algorithm> 7 using namespace std; 8 9 int main() 10 { 11 int ival , searchValue; 12 vector<int> ivec; 13 14 //读入int型数据并存储到vector对象中,直至遇到文件结束符 15 cout<<"Enter some integers(Ctrl+Z to end): "<<endl; 16 while(cin >> ival) 17 ivec.push_back(ival); 18 19 cin.clear(); // 使输入流重新有效 20 21 //读入欲统计其出现次数的int值 22 cout<<"Enter an integer you want to search: "<<endl; 23 cin>>searchValue; 24 25 //使用count函数统计该值出现的次数并输出结果 26 cout<<count(ivec.begin() , ivec.end() , searchValue) 27 <<" elements in the vector have value " 28 <<searchValue<<endl; 29 30 return 0; 31 }

浙公网安备 33010602011771号