• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. Copyright David Abrahams 2006. Distributed under the Boost
2.. Software License, Version 1.0. (See accompanying
3.. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
4
5Example
6.......
7
8This is a simple example of using the transform_iterators class to
9generate iterators that multiply (or add to) the value returned by
10dereferencing the iterator. It would be cooler to use lambda library
11in this example.
12
13::
14
15    int x[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
16    const int N = sizeof(x)/sizeof(int);
17
18    typedef boost::binder1st< std::multiplies<int> > Function;
19    typedef boost::transform_iterator<Function, int*> doubling_iterator;
20
21    doubling_iterator i(x, boost::bind1st(std::multiplies<int>(), 2)),
22      i_end(x + N, boost::bind1st(std::multiplies<int>(), 2));
23
24    std::cout << "multiplying the array by 2:" << std::endl;
25    while (i != i_end)
26      std::cout << *i++ << " ";
27    std::cout << std::endl;
28
29    std::cout << "adding 4 to each element in the array:" << std::endl;
30    std::copy(boost::make_transform_iterator(x, boost::bind1st(std::plus<int>(), 4)),
31	      boost::make_transform_iterator(x + N, boost::bind1st(std::plus<int>(), 4)),
32	      std::ostream_iterator<int>(std::cout, " "));
33    std::cout << std::endl;
34
35
36The output is::
37
38    multiplying the array by 2:
39    2 4 6 8 10 12 14 16
40    adding 4 to each element in the array:
41    5 6 7 8 9 10 11 12
42
43
44The source code for this example can be found `here`__.
45
46__ ../example/transform_iterator_example.cpp
47