• 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 example prints an array of characters, using
9``indirect_iterator`` to access the array of characters through an
10array of pointers. Next ``indirect_iterator`` is used with the
11``transform`` algorithm to copy the characters (incremented by one) to
12another array. A constant indirect iterator is used for the source and
13a mutable indirect iterator is used for the destination. The last part
14of the example prints the original array of characters, but this time
15using the ``make_indirect_iterator`` helper function.
16
17
18::
19
20    char characters[] = "abcdefg";
21    const int N = sizeof(characters)/sizeof(char) - 1; // -1 since characters has a null char
22    char* pointers_to_chars[N];                        // at the end.
23    for (int i = 0; i < N; ++i)
24      pointers_to_chars[i] = &characters[i];
25
26    // Example of using indirect_iterator
27
28    boost::indirect_iterator<char**, char>
29      indirect_first(pointers_to_chars), indirect_last(pointers_to_chars + N);
30
31    std::copy(indirect_first, indirect_last, std::ostream_iterator<char>(std::cout, ","));
32    std::cout << std::endl;
33
34
35    // Example of making mutable and constant indirect iterators
36
37    char mutable_characters[N];
38    char* pointers_to_mutable_chars[N];
39    for (int j = 0; j < N; ++j)
40      pointers_to_mutable_chars[j] = &mutable_characters[j];
41
42    boost::indirect_iterator<char* const*> mutable_indirect_first(pointers_to_mutable_chars),
43      mutable_indirect_last(pointers_to_mutable_chars + N);
44    boost::indirect_iterator<char* const*, char const> const_indirect_first(pointers_to_chars),
45      const_indirect_last(pointers_to_chars + N);
46
47    std::transform(const_indirect_first, const_indirect_last,
48		   mutable_indirect_first, std::bind1st(std::plus<char>(), 1));
49
50    std::copy(mutable_indirect_first, mutable_indirect_last,
51	      std::ostream_iterator<char>(std::cout, ","));
52    std::cout << std::endl;
53
54
55    // Example of using make_indirect_iterator()
56
57    std::copy(boost::make_indirect_iterator(pointers_to_chars),
58	      boost::make_indirect_iterator(pointers_to_chars + N),
59	      std::ostream_iterator<char>(std::cout, ","));
60    std::cout << std::endl;
61
62
63The output is::
64
65    a,b,c,d,e,f,g,
66    b,c,d,e,f,g,h,
67    a,b,c,d,e,f,g,
68
69
70The source code for this example can be found `here`__.
71
72__ ../example/indirect_iterator_example.cpp
73
74