转载自:http://www.dreamincode.net/forums/topic/52509-stl-algorithmcount/
What do I need to know before studying this tutorial?
You should have a knowledge of vectors and vector iterators.
What does the count() algorithm do?
It counts the # of a specified value within a vector
The syntax for the count() algorithm:
int count = count(<where to begin searching>, <where to stop searching>, <value to search for>);
What to include:
#include <iostream> // just to output what's going on #include <algorithm> // algorithms! #include <vector> // vector to use algorithms on using namespace std;
vector <int> myVec; // create a vector called myVec vector <int> :: iterator it; // create a vector iterator called it
for (int i = 0; i < 9; ++i) { int random = rand () % 5; // generate a random number myVec.push_back(random); // fill the vector with some values }
cout << "Contents: "; for (it = myVec.begin(); it != myVec.end(); ++it) cout << *it << " "; // print the contents of myVec
int count_value = count (myVec.begin(), myVec.end(), 4);
cout << endl << "Number of 4s stored in vector: " << count_value; cin.get (); // pause return EXIT_SUCCESS; // everything went OK
#include <iostream> // just to output what's going on #include <algorithm> // algorithms! #include <vector> // vector to use algorithms on using namespace std; int main () { vector <int> myVec; // create a vector called myVec vector <int> :: iterator it; // create a vector iterator called it for (int i = 0; i < 9; ++i) { int random = rand () % 5; // generate a random number myVec.push_back(random); // fill the vector with some values } cout << "Contents: "; for (it = myVec.begin(); it != myVec.end(); ++it) cout << *it << " "; // print the contents of myVec int count_value = count (myVec.begin(), myVec.end(), 4); cout << endl << "Number of 4s stored in vector: " << count_value; cin.get (); // pause return EXIT_SUCCESS; // everything went OK }