Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
count.cpp
Go to the documentation of this file.
1
29#include <algorithm> // for count, count_if
30#include <cassert> // for assert
31#include <functional> // bind2nd, less
32#include <iostream> // for cout
33#include <iterator> // for ostream_iterator
34#include <vector> // for vector
35
36#include <examples.h>
37
38
39// streams out a vector
40template <class T>
41std::ostream&
42operator<< (std::ostream &out,
43 const std::vector<T, std::allocator<T> > &vec)
44{
45 typedef std::ostream_iterator<T, char, std::char_traits<char> > Iter;
46
47 out << "{ ";
48
49 std::copy (vec.begin (), vec.end (), Iter (out, " "));
50
51 out << "}";
52
53 return out;
54}
55
56
57int main ()
58{
59 // Typedef for convenience.
60 typedef std::vector<short, std::allocator<short> > Vector;
61
62 const Vector::value_type a [] = { 1, 2, 3, 4, 5, 5, 7, 8, 9, 10 };
63
64 // construct a vector from the array
65 const Vector vec (a + 0, a + 10);
66
67 Vector::size_type n_fives = 0;
68 Vector::size_type n_sixes = 0;
69 Vector::size_type n_lt_8 = 0;
70
71#ifndef _RWSTD_NO_EXT_VOID_COUNT
72
73 // using the extended overloads of function template count()
74 // and count_if() provided by this implmentation, count the
75 // number of fives, sixes, and values less than 8 in the
76 // sequence
77
78 std::count (vec.begin (), vec.end (), 5, n_fives);
79 std::count (vec.begin (), vec.end (), 6, n_sixes);
80
81 std::count_if (vec.begin (), vec.end (),
82 std::bind2nd (std::less<Vector::value_type>(), 8),
83 n_lt_8);
84
85 assert (2 == n_fives);
86 assert (0 == n_sixes);
87 assert (7 == n_lt_8);
88
89#endif // _RWSTD_NO_EXT_VOID_COUNT
90
91 // do the same using the standard function templates count()
92 // and count_if()
93
94 n_fives = std::count (vec.begin (), vec.end (), 5);
95 n_sixes = std::count (vec.begin (), vec.end (), 6);
96 n_lt_8 = std::count_if (vec.begin (), vec.end (),
97 std::bind2nd (std::less<Vector::value_type>(), 8));
98
99 std::cout << "sequence: " << vec;
100 std::cout << "\nnumber of fives: " << n_fives
101 << "\nnumber of sixes: " << n_sixes
102 << "\nnumber of values less than 8: " << n_lt_8 << '\n';
103
104 return 0;
105}
#define T
Definition 17.names.cpp:163
#define a
Definition 17.names.cpp:109
std::vector< UserClass, std::allocator< UserClass > > Vector
const int out
#define assert(expr)
Definition _cassert.h:40
std::ostream_iterator< int, char, std::char_traits< char > > Iter
Definition alg7.cpp:64
std::ostream & operator<<(std::ostream &out, const std::vector< T, std::allocator< T > > &vec)
Definition count.cpp:42
int main()
Definition count.cpp:57