permutation_iterator_eg.rst 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. ::
  5. using namespace boost;
  6. int i = 0;
  7. typedef std::vector< int > element_range_type;
  8. typedef std::list< int > index_type;
  9. static const int element_range_size = 10;
  10. static const int index_size = 4;
  11. element_range_type elements( element_range_size );
  12. for(element_range_type::iterator el_it = elements.begin() ; el_it != elements.end() ; ++el_it)
  13. *el_it = std::distance(elements.begin(), el_it);
  14. index_type indices( index_size );
  15. for(index_type::iterator i_it = indices.begin() ; i_it != indices.end() ; ++i_it )
  16. *i_it = element_range_size - index_size + std::distance(indices.begin(), i_it);
  17. std::reverse( indices.begin(), indices.end() );
  18. typedef permutation_iterator< element_range_type::iterator, index_type::iterator > permutation_type;
  19. permutation_type begin = make_permutation_iterator( elements.begin(), indices.begin() );
  20. permutation_type it = begin;
  21. permutation_type end = make_permutation_iterator( elements.begin(), indices.end() );
  22. std::cout << "The original range is : ";
  23. std::copy( elements.begin(), elements.end(), std::ostream_iterator< int >( std::cout, " " ) );
  24. std::cout << "\n";
  25. std::cout << "The reindexing scheme is : ";
  26. std::copy( indices.begin(), indices.end(), std::ostream_iterator< int >( std::cout, " " ) );
  27. std::cout << "\n";
  28. std::cout << "The permutated range is : ";
  29. std::copy( begin, end, std::ostream_iterator< int >( std::cout, " " ) );
  30. std::cout << "\n";
  31. std::cout << "Elements at even indices in the permutation : ";
  32. it = begin;
  33. for(i = 0; i < index_size / 2 ; ++i, it+=2 ) std::cout << *it << " ";
  34. std::cout << "\n";
  35. std::cout << "Permutation backwards : ";
  36. it = begin + (index_size);
  37. assert( it != begin );
  38. for( ; it-- != begin ; ) std::cout << *it << " ";
  39. std::cout << "\n";
  40. std::cout << "Iterate backward with stride 2 : ";
  41. it = begin + (index_size - 1);
  42. for(i = 0 ; i < index_size / 2 ; ++i, it-=2 ) std::cout << *it << " ";
  43. std::cout << "\n";
  44. The output is::
  45. The original range is : 0 1 2 3 4 5 6 7 8 9
  46. The reindexing scheme is : 9 8 7 6
  47. The permutated range is : 9 8 7 6
  48. Elements at even indices in the permutation : 9 7
  49. Permutation backwards : 6 7 8 9
  50. Iterate backward with stride 2 : 6 8
  51. The source code for this example can be found `here`__.
  52. __ ../example/permutation_iter_example.cpp