Skip to content

Instantly share code, notes, and snippets.

@supr
Created May 9, 2014 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supr/ef4c4377c24e57508cd7 to your computer and use it in GitHub Desktop.
Save supr/ef4c4377c24e57508cd7 to your computer and use it in GitHub Desktop.
C++11 Algorithm example
/*
C++11 Algorithm example
Compile: clang++ -std=c++11 -static this.cc
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
int numbers[] = {1, 2, 42, 7, 0};
std::vector<std::string> words = { "", "to", "be", "or", "not", "at"};
int main(void)
{
auto is_positive = [](int const n){return n >= 0;};
auto is_zero = [](int const n){return n == 0;};
auto is_empty = [](std::string const & s){ return s.empty();};
auto smaller_length = [](std::string const & first, std::string const & second){ return first.length() < second.length(); };
std::cout << "All Positive: " << std::boolalpha
<< std::all_of(std::begin(numbers), std::end(numbers), is_positive)
<< std::endl;
std::cout << "Any Zero: " << std::boolalpha
<< std::any_of(std::begin(numbers), std::end(numbers), is_zero)
<< std::endl;
std::cout << "None Empty: " << std::boolalpha
<< std::none_of(std::begin(words), std::end(words), is_empty)
<< std::endl;
std::cout << "Sorted: " << std::boolalpha
<< std::is_sorted(std::begin(numbers), std::end(numbers))
<< std::endl;
std::cout << "Sorted by Length: " << std::boolalpha
<< std::is_sorted(std::begin(words), std::end(words), smaller_length)
<< std::endl;
auto last_int = std::is_sorted_until(std::begin(numbers), std::end(numbers));
auto last_str = std::is_sorted_until(std::begin(words), std::end(words), smaller_length);
std::cout << "(int) Sorted Until: " << std::endl
<< "upper bound = " << *(last_int - 1) << std::endl
<< "sort size = " << std::distance(std::begin(numbers), last_int) << std::endl;
std::cout << "(str) Sorted Until: " << std::endl
<< "upper bound = " << *(last_str - 1) << std::endl
<< "sort size = " << std::distance(std::begin(words), last_str) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment