algorithm_example.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Boost.Range library
  2. //
  3. // Copyright Thorsten Ottosen 2003-2004. Use, modification and
  4. // distribution is subject to the Boost Software License, Version
  5. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // For more information, see http://www.boost.org/libs/range/
  9. //
  10. #include <boost/detail/workaround.hpp>
  11. #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
  12. # pragma warn -8091 // suppress warning in Boost.Test
  13. # pragma warn -8057 // unused argument argc/argv in Boost.Test
  14. #endif
  15. #include <boost/range/functions.hpp>
  16. #include <boost/range/metafunctions.hpp>
  17. #include <boost/range/as_literal.hpp>
  18. #include <boost/test/test_tools.hpp>
  19. #include <iostream>
  20. #include <algorithm>
  21. #include <vector>
  22. #include <utility>
  23. namespace
  24. {
  25. //
  26. // example: extracting bounds in a generic algorithm
  27. //
  28. template< typename Range, typename T >
  29. inline typename boost::range_iterator<Range>::type
  30. find( Range& c, const T& value )
  31. {
  32. return std::find( boost::begin( c ), boost::end( c ), value );
  33. }
  34. template< typename Range, typename T >
  35. inline typename boost::range_iterator<Range>::type
  36. find( const Range& c, const T& value )
  37. {
  38. return std::find( boost::begin( c ), boost::end( c ), value );
  39. }
  40. //
  41. // replace first value and return its index
  42. //
  43. template< class Range, class T >
  44. inline typename boost::range_difference<Range>::type
  45. my_generic_replace( Range& c, const T& value, const T& replacement )
  46. {
  47. typename boost::range_iterator<Range>::type found = find( c, value );
  48. if( found != boost::end( c ) )
  49. *found = replacement;
  50. return std::distance( boost::begin( c ), found );
  51. }
  52. }
  53. void check_algorithm()
  54. {
  55. //
  56. // usage
  57. //
  58. const int N = 5;
  59. std::vector<int> my_vector;
  60. int values[] = { 1,2,3,4,5,6,7,8,9 };
  61. my_vector.assign( values, values + 9 );
  62. typedef std::vector<int>::iterator iterator;
  63. std::pair<iterator,iterator> my_view( boost::begin( my_vector ),
  64. boost::begin( my_vector ) + N );
  65. BOOST_CHECK_EQUAL( my_generic_replace( my_vector, 4, 2 ), 3 );
  66. BOOST_CHECK_EQUAL( my_generic_replace( my_view, 4, 2 ), N );
  67. }
  68. #include <boost/test/unit_test.hpp>
  69. using boost::unit_test::test_suite;
  70. test_suite* init_unit_test_suite( int argc, char* argv[] )
  71. {
  72. test_suite* test = BOOST_TEST_SUITE( "Range Test Suite" );
  73. test->add( BOOST_TEST_CASE( &check_algorithm ) );
  74. return test;
  75. }