Last active
July 25, 2018 18:58
-
-
Save doug-numetric/d5518ffe627c686eec7e927403611110 to your computer and use it in GitHub Desktop.
modern c++
This file contains hidden or 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
// compile with c++ --std=c++17 ./c++17.cpp | |
#include <iostream> | |
#include <vector> | |
#include <stdexcept> | |
#include <tuple> | |
#include <type_traits> | |
template <class T> using il = std::initializer_list<T>; | |
auto reduce = [](const auto& reducer, const auto& collection, auto&& init) -> auto { | |
for (auto& e : collection) { | |
reducer(init, e); | |
} | |
return init; | |
}; | |
auto slice = [](auto&& input, int beg, int end) -> decltype(auto) { | |
using T = typename std::remove_reference<decltype(input)>::type; | |
const auto size = input.size(); | |
if (beg > size || end > size || beg < 0 || end < 0) { | |
throw std::out_of_range("beg/end must be between [0, input.size())"); | |
} | |
if (beg > end) { | |
throw std::invalid_argument("beg must be less than end"); | |
} | |
return T(input.begin() + beg, input.begin() + end); | |
}; | |
int fibonacci(int value) { | |
auto [ a, b ] = std::tuple{ 1, 1 }; | |
for (int i = 0; i < value; i++) { | |
std::tie(a, b) = std::tuple{ b, a+b }; | |
} | |
return b; | |
}; | |
int main() { | |
std::cout << "fib 5 is: " << fibonacci(5) << std::endl; | |
std::cout << "sum is: " << reduce( | |
[](auto& acc, const auto& cv){ acc *= cv; }, | |
il<int>{2,2,2,2,2}, | |
1 | |
) << std::endl; | |
auto v = std::vector<int> { 1,2,3,4,5 }; | |
std::cout << "slice: "; | |
for (auto e : slice(v, 1, 4)) { | |
std::cout << e << " "; | |
} | |
std::cout << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I find being able to write c++ that looks like this weirdly satisfying...