replace_if.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Boost.Range library
  2. //
  3. // Copyright Neil Groves 2009. 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. //
  9. // For more information, see http://www.boost.org/libs/range/
  10. //
  11. #include <boost/range/algorithm/replace_if.hpp>
  12. #include <boost/test/test_tools.hpp>
  13. #include <boost/test/unit_test.hpp>
  14. #include <boost/assign.hpp>
  15. #include <boost/bind.hpp>
  16. #include <algorithm>
  17. #include <functional>
  18. #include <list>
  19. #include <numeric>
  20. #include <deque>
  21. #include <vector>
  22. namespace boost
  23. {
  24. namespace
  25. {
  26. template< class Container, class UnaryPredicate >
  27. void test_replace_if_impl(Container& cont, UnaryPredicate pred)
  28. {
  29. const int what = 2;
  30. const int with_what = 5;
  31. std::vector<int> reference(cont.begin(), cont.end());
  32. std::replace_if(reference.begin(), reference.end(),
  33. boost::bind(pred, _1, what), with_what);
  34. std::vector<int> target(cont.begin(), cont.end());
  35. boost::replace_if(target, boost::bind(pred, _1, what), with_what);
  36. BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(),
  37. target.begin(), target.end() );
  38. std::vector<int> target2(cont.begin(), cont.end());
  39. boost::replace_if(boost::make_iterator_range(target2),
  40. boost::bind(pred, _1, what), with_what);
  41. BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(),
  42. target2.begin(), target2.end() );
  43. }
  44. template< class Container >
  45. void test_replace_if_impl(Container& cont)
  46. {
  47. test_replace_if_impl(cont, std::equal_to<int>());
  48. test_replace_if_impl(cont, std::not_equal_to<int>());
  49. }
  50. template< class Container >
  51. void test_replace_if_impl()
  52. {
  53. using namespace boost::assign;
  54. Container cont;
  55. test_replace_if_impl(cont);
  56. cont.clear();
  57. cont += 1;
  58. test_replace_if_impl(cont);
  59. cont.clear();
  60. cont += 1,2,3,4,5,6,7,8,9;
  61. test_replace_if_impl(cont);
  62. }
  63. void test_replace_if()
  64. {
  65. test_replace_if_impl< std::vector<int> >();
  66. test_replace_if_impl< std::list<int> >();
  67. test_replace_if_impl< std::deque<int> >();
  68. }
  69. }
  70. }
  71. boost::unit_test::test_suite*
  72. init_unit_test_suite(int argc, char* argv[])
  73. {
  74. boost::unit_test::test_suite* test
  75. = BOOST_TEST_SUITE( "RangeTestSuite.algorithm.replace_if" );
  76. test->add( BOOST_TEST_CASE( &boost::test_replace_if ) );
  77. return test;
  78. }