Last active
February 22, 2016 21:56
Examples using Standard library Algorithms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#if __cplusplus > 201103L | |
// for C++14 use | |
using std::cbegin; | |
using std::cend; | |
#else | |
// C++11 does not implement non-member version of cbegin and cend. | |
// Therefor for a C++11 only compiler use | |
template<class C> | |
auto cbegin(const C& container)->decltype(std::begin(container)) { | |
// invoking the non-member begin function on a const container yields a const-iterator. | |
return std::begin(container); | |
} | |
template<class C> | |
auto cend(const C& container)->decltype(std::end(container)) { | |
// invoking the non-member end function on a const container yields a const-iterator. | |
return std::end(container); | |
} | |
#endif | |
template<typename C> | |
void sort_ascending(C& container) { | |
using std::begin; | |
using std::end; | |
std::sort(std::begin(container), std::end(container)); | |
} | |
template<typename C> | |
void sort_descending(C& container) { | |
using std::begin; | |
using std::end; | |
std::sort(std::begin(container), std::end(container), std::greater<typename C::value_type>()); | |
} | |
template<class C> | |
void sort_and_remove_duplicates(C& container) { | |
using std::begin; | |
using std::end; | |
std::sort(begin(container), end(container)); | |
container.erase(std::unique(begin(container), end(container)), end(container)); | |
} | |
template<class C> | |
bool has_even_elements(C& container) { | |
return std::any_of(cbegin(container), cend(container), [](int i){ return i % 2 == 0; })); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment