minmax_test.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // (C) Copyright Herve Bronnimann 2004.
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #include <utility>
  6. #include <functional>
  7. #include <boost/config.hpp>
  8. #include <boost/algorithm/minmax.hpp>
  9. #define BOOST_TEST_MAIN
  10. #include <boost/test/unit_test.hpp>
  11. class custom {
  12. int m_x;
  13. friend std::ostream& operator<<(std::ostream& str, custom const& x);
  14. public:
  15. explicit custom(int x = 0) : m_x(x) {}
  16. custom(custom const& y) : m_x(y.m_x) {}
  17. bool operator==(custom const& y) const { return m_x == y.m_x; }
  18. bool operator<(custom const& y) const { return m_x < y.m_x; }
  19. custom operator+(custom const& y) const { return custom(m_x+y.m_x); }
  20. custom& operator+=(custom const& y) { m_x += y.m_x; return *this; }
  21. };
  22. std::ostream&
  23. operator<<(std::ostream& str, custom const& x)
  24. {
  25. return str << x.m_x;
  26. }
  27. template <class Value>
  28. struct less_count : std::less<Value> {
  29. typedef std::less<Value> Base;
  30. less_count(less_count<Value> const& lc) : m_counter(lc.m_counter) {}
  31. less_count(int& counter) : m_counter(counter) {}
  32. bool operator()(Value const& a, Value const& b) const {
  33. ++m_counter;
  34. return Base::operator()(a,b);
  35. }
  36. void reset() {
  37. m_counter = 0;
  38. }
  39. private:
  40. int& m_counter;
  41. };
  42. using namespace boost;
  43. template <class Value>
  44. void test(BOOST_EXPLICIT_TEMPLATE_TYPE(Value))
  45. {
  46. Value zero(0), one(1);
  47. int counter = 0;
  48. less_count<Value> lc(counter);
  49. // Test functionality
  50. tuple<Value const&, Value const&> result1 = boost::minmax(zero, one);
  51. BOOST_CHECK_EQUAL( get<0>(result1), zero );
  52. BOOST_CHECK_EQUAL( get<1>(result1), one );
  53. tuple<Value const&, Value const&> result2 = boost::minmax(one, zero);
  54. BOOST_CHECK_EQUAL( get<0>(result2), zero );
  55. BOOST_CHECK_EQUAL( get<1>(result2), one );
  56. // Test functionality and number of comparisons
  57. lc.reset();
  58. tuple<Value const&, Value const&> result3 = boost::minmax(zero, one, lc );
  59. BOOST_CHECK_EQUAL( get<0>(result3), zero );
  60. BOOST_CHECK_EQUAL( get<1>(result3), one );
  61. BOOST_CHECK_EQUAL( counter, 1 );
  62. lc.reset();
  63. tuple<Value const&, Value const&> result4 = boost::minmax(one, zero, lc );
  64. BOOST_CHECK_EQUAL( get<0>(result4), zero );
  65. BOOST_CHECK_EQUAL( get<1>(result4), one );
  66. BOOST_CHECK_EQUAL( counter, 1);
  67. }
  68. BOOST_AUTO_TEST_CASE( test_main )
  69. {
  70. test<int>(); // ("builtin");
  71. test<custom>(); // ("custom ");
  72. }