Skip to content

Instantly share code, notes, and snippets.

@meshell
Last active February 22, 2016 21:56
Show Gist options
  • Save meshell/6ecda73ed0ac921cbdd6 to your computer and use it in GitHub Desktop.
Save meshell/6ecda73ed0ac921cbdd6 to your computer and use it in GitHub Desktop.
Examples using Standard library Algorithms
#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