Rosetta
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
iter_util.hh
Go to the documentation of this file.
1 // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
2 // vi: set ts=2 noet:
3 //
4 // (c) Copyright Rosetta Commons Member Institutions.
5 // (c) This file is part of the Rosetta software suite and is made available under license.
6 // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
7 // (c) For more information, see http://www.rosettacommons.org. Questions about this can be
8 // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu.
9 
10 /// @file utility/iter_util.hh
11 /// @author Christopher Miles (cmiles@uw.edu)
12 
13 #ifndef INCLUDED_UTILITY_ITER_UTIL_hh
14 #define INCLUDED_UTILITY_ITER_UTIL_hh
15 
16 // C/C++ headers
17 #include <algorithm>
18 #include <iterator>
19 
20 namespace utility {
21 
22 /// @brief Returns an iterator on the sorted range [first, last) nearest
23 /// to value. If value is equidistant between adjacent elements, the
24 /// lesser is returned.
25 template <typename BidirectionalIterator, typename T>
26 BidirectionalIterator find_closest(BidirectionalIterator first,
27  BidirectionalIterator last,
28  const T& value) {
29  BidirectionalIterator before = std::lower_bound(first, last, value);
30 
31  if ( before == first ) return first;
32  if ( before == last ) return --last; // iterator must be bidirectional
33 
34  BidirectionalIterator after = before;
35  --before;
36 
37  return (*after - value) < (value - *before) ? after : before;
38 }
39 
40 } // namespace utility
41 
42 #endif // INCLUDED_UTILITY_ITER_UTIL_hh
member1 value
Definition: Tag.cc:296
BidirectionalIterator find_closest(BidirectionalIterator first, BidirectionalIterator last, const T &value)
Returns an iterator on the sorted range [first, last) nearest to value. If value is equidistant betwe...
Definition: iter_util.hh:26