Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
All containers have a member function size( )
that tells you how many elements they hold. The return type of size( )
is the iterator s difference_type (usually
ptrdiff_t), which we denote by IntegralValue in the following.
The following two algorithms count objects that satisfy certain criteria.
IntegralValue count(InputIterator
first, InputIterator
last, const EqualityComparable& value);
Produces the number of elements in [first, last) that
are equivalent to value (when tested using operator==).
IntegralValue count_if(InputIterator
first, InputIterator
last, Predicate pred);
Produces the number of elements in [first, last)
that each cause pred to return true.
Example
Here, a vector<char> v is filled with
random characters (including some duplicates). A set<char> is
initialized from v, so it holds only one of each letter represented in v.
This set counts all the instances of all the characters, which are then
displayed:
//: C06:Counting.cpp
// The counting algorithms.
//{L} Generators
#include <algorithm>
#include <functional>
#include <iterator>
#include <set>
#include <vector>
#include "Generators.h"
#include "PrintSequence.h"
using namespace std;
int main() {
vector<char> v;
generate_n(back_inserter(v), 50, CharGen());
print(v.begin(), v.end(), "v",
"");
// Create a set of the characters in v:
set<char> cs(v.begin(), v.end());
typedef set<char>::iterator sci;
for(sci it = cs.begin(); it != cs.end(); it++) {
int n = count(v.begin(), v.end(), *it);
cout << *it << ": " <<
n << ", ";
}
int lc = count_if(v.begin(), v.end(),
bind2nd(greater<char>(), 'a'));
cout << "\nLowercase letters: "
<< lc << endl;
sort(v.begin(), v.end());
print(v.begin(), v.end(), "sorted",
"");
} ///:~
The count_if( ) algorithm is demonstrated by
counting all the lowercase letters; the predicate is created using the bind2nd( ) and greater function object templates.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |