1 #ifndef GENESIS_UTILS_CORE_ALGORITHM_H_
2 #define GENESIS_UTILS_CORE_ALGORITHM_H_
39 #include <unordered_set>
55 template<
class ForwardIt,
class T,
class Compare=std::less<T>>
56 ForwardIt
binary_find(ForwardIt first, ForwardIt last,
const T& value, Compare comp={})
62 first = std::lower_bound(first, last, value, comp);
63 return first != last && !comp(value, *first) ? first : last;
73 template<
class C,
class T>
76 return std::end(v) != std::find(std::begin(v), std::end(v), x);
88 auto test = std::unordered_set< typename C::value_type >();
89 for(
auto const& e : v ) {
90 if( test.count(e) > 0 ) {
106 template<
class Container,
class UnaryPredicate >
107 inline void erase_if( Container &c, UnaryPredicate p )
111 using std::remove_if;
113 auto old_end = end( c );
114 auto new_end = remove_if( begin( c ), old_end, p );
116 if ( new_end != old_end ) {
117 c.erase( new_end, old_end );
130 return (a < b) ? std::pair<T, T>(a, b) : std::pair<T, T>(b, a);
136 template<
class T,
class Compare>
139 return comp(a, b) ? std::pair<T, T>(a, b) : std::pair<T, T>(b, a);
150 template<
typename T >
151 typename std::vector<T>::iterator
155 std::upper_bound( vec.begin(), vec.end(), item ),
164 template<
typename T,
typename Pred >
165 typename std::vector<T>::iterator
169 std::upper_bound( vec.begin(), vec.end(), item, pred ),
181 template <
typename RandomAccessIterator,
typename Comparator>
183 RandomAccessIterator first,
184 RandomAccessIterator last,
185 Comparator comparator
188 size_t size = std::distance( first, last );
189 std::vector<size_t> idx( size );
190 std::iota( idx.begin(), idx.end(),
static_cast<size_t>(0) );
193 std::sort( idx.begin(), idx.end(), [&] (
size_t i1,
size_t i2 ) {
194 assert( first + i1 < last );
195 assert( first + i2 < last );
196 return comparator( *(first + i1), *(first + i2) );
223 template <
typename RandomAccessIterator>
225 RandomAccessIterator first,
226 RandomAccessIterator last
231 std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type >()
238 template <
typename RandomAccessIterator,
typename Comparator>
240 RandomAccessIterator first,
241 RandomAccessIterator last,
242 Comparator comparator
245 size_t size = std::distance( first, last );
246 std::vector<size_t> idx( size );
247 std::iota( idx.begin(), idx.end(),
static_cast<size_t>(0) );
250 std::stable_sort( idx.begin(), idx.end(), [&] (
size_t i1,
size_t i2 ) {
251 assert( first + i1 < last );
252 assert( first + i2 < last );
253 return comparator( *(first + i1), *(first + i2) );
280 template <
typename RandomAccessIterator>
282 RandomAccessIterator first,
283 RandomAccessIterator last
288 std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type >()
295 #endif // include guard