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