clamp_example.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. Copyright (c) Marshall Clow 2010-2012.
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. For more information, see http://www.boost.org
  6. */
  7. #include <string>
  8. #include <iostream> // for cout, etc
  9. #include <boost/algorithm/clamp.hpp>
  10. namespace ba = boost::algorithm;
  11. bool compare_string_lengths ( const std::string &one, const std::string &two )
  12. {
  13. return one.length () < two.length ();
  14. }
  15. int main ( int /*argc*/, char * /*argv*/ [] ) {
  16. // Clamp takes a value and two "fenceposts", and brings the value "between" the fenceposts.
  17. // If the input value is "between" the fenceposts, then it is returned unchanged.
  18. std::cout << "Clamping 5 to between [1, 10] -> " << ba::clamp ( 5, 1, 10 ) << std::endl;
  19. // If the input value is out side the range of the fenceposts, it "brought into" range.
  20. std::cout << "Clamping 15 to between [1, 10] -> " << ba::clamp ( 15, 1, 10 ) << std::endl;
  21. std::cout << "Clamping -15 to between [1, 10] -> " << ba::clamp ( -15, 1, 10 ) << std::endl;
  22. // It doesn't just work for ints
  23. std::cout << "Clamping 5.1 to between [1, 10] -> " << ba::clamp ( 5.1, 1.0, 10.0 ) << std::endl;
  24. {
  25. std::string one ( "Lower Bound" ), two ( "upper bound!" ), test1 ( "test#" ), test2 ( "#test" );
  26. std::cout << "Clamping '" << test1 << "' between ['" << one << "' and '" << two << "'] -> '" <<
  27. ba::clamp ( test1, one, two ) << "'" << std::endl;
  28. std::cout << "Clamping '" << test2 << "' between ['" << one << "' and '" << two << "'] -> '" <<
  29. ba::clamp ( test2, one, two ) << "'" << std::endl;
  30. // There is also a predicate based version, if you want to compare objects in your own way
  31. std::cout << "Clamping '" << test1 << "' between ['" << one << "' and '" << two << "'] (comparing lengths) -> '" <<
  32. ba::clamp ( test1, one, two, compare_string_lengths ) << "'" << std::endl;
  33. std::cout << "Clamping '" << test2 << "' between ['" << one << "' and '" << two << "'] (comparing lengths) -> '" <<
  34. ba::clamp ( test2, one, two, compare_string_lengths ) << "'" << std::endl;
  35. }
  36. // Sometimes, though, you don't get quite what you expect
  37. // This is because the two double arguments get converted to int
  38. std::cout << "Somewhat unexpected: clamp ( 12, 14.7, 15.9 ) --> " << ba::clamp ( 12, 14.7, 15.9 ) << std::endl;
  39. std::cout << "Expected: clamp ((double)12, 14.7, 15.9 ) --> " << ba::clamp ((double) 12, 14.7, 15.9 ) << std::endl;
  40. return 0;
  41. }