Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
binders.cpp
Go to the documentation of this file.
1
29#include <algorithm> // for find_if
30#include <functional> // for equal_to, bind1st, bind2nd
31#include <iostream> // for cout
32#include <iterator> // for ostream_iterator
33#include <vector> // for vector
34
35#include <examples.h>
36
37
38int main ()
39{
40 typedef std::vector<int> Vector;
41 typedef std::equal_to<Vector::value_type> EqualTo;
42
43 const Vector::value_type arr [] = { 1, 2, 3, 4, 5 };
44
45 // Initialize a vector with the array elements.
46 const Vector v1 (arr, arr + sizeof arr / sizeof *arr);
47
48 // Value to look for.
49 const Vector::value_type x (3);
50
51 // Create an 'equal to 3' unary predicate by binding the value
52 // 3 to the EqualTo binary predicate.
53 const std::binder1st<EqualTo> equal_to_3 (std::bind1st (EqualTo (), x));
54
55 // Now use this new predicate in a call to find_if.
56 const Vector::const_iterator it1 =
57 std::find_if (v1.begin (), v1.end (), equal_to_3);
58
59 // Even better, construct the new predicate on the fly.
60 const Vector::const_iterator it2 =
61 std::find_if (v1.begin (), v1.end (), std::bind1st (EqualTo (), x));
62
63 // And now the same thing using bind2nd.
64 // Same result since EqualTo is commutative.
65 const Vector::const_iterator it3 =
66 std::find_if (v1.begin (), v1.end (), std::bind2nd (EqualTo (), x));
67
68 // Use the same predicate to count the number of elements
69 // equal to 3.
70 const Vector::size_type n =
71 std::count_if (v1.begin (), v1.end (), std::bind2nd (EqualTo (), x));
72
73 // Output results.
74 std::ostream_iterator<Vector::value_type> out (std::cout, " ");
75
76 std::cout << "The vector { ";
77 std::copy (v1.begin (), v1.end (), out);
78
79 std::cout << "} contains " << n << " element equal to " << x
80 << " at offset " << it1 - v1.begin () << ".\n";
81
82 // Exit with status of 0 on success, 1 on failure.
83 const bool success = 1 == n && it1 == it2 && it1 == it2 && *it1 == x;
84
85 return success ? 0 : 1;
86}
#define x
Definition 17.names.cpp:140
#define n
Definition 17.names.cpp:130
#define v1
Definition 17.names.cpp:245
std::vector< UserClass, std::allocator< UserClass > > Vector
const int out
int main()
Definition binders.cpp:38