Created
May 3, 2014 16:55
-
-
Save socantre/db01e449d3bb8640addc to your computer and use it in GitHub Desktop.
for (auto &&kv : enumerate(x))
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
| #include <vector> | |
| #include <iostream> | |
| #include <tuple> | |
| #include <functional> | |
| template<typename Container> | |
| struct enumerate_iterator { | |
| typename Container::size_type i; | |
| typename Container::iterator v; | |
| bool operator!=(enumerate_iterator const &rhs) { return i != rhs.i; } | |
| enumerate_iterator &operator++() { | |
| ++i; | |
| ++v; | |
| return *this; | |
| } | |
| auto operator*() { return std::make_tuple(i, std::ref(*v)); } | |
| }; | |
| template <typename Container> struct enumerate_impl { | |
| Container c; | |
| auto begin() { | |
| return enumerate_iterator<Container>{0, c.begin()}; | |
| } | |
| auto end() { | |
| return enumerate_iterator<Container>{c.size(), c.end()}; | |
| } | |
| }; | |
| template <typename Container> struct enumerate_impl<Container &> { | |
| Container &c; | |
| auto begin() { | |
| return enumerate_iterator<Container>{0, c.begin()}; | |
| } | |
| auto end() { | |
| return enumerate_iterator<Container>{c.size(), c.end()}; | |
| } | |
| }; | |
| template <typename Container> | |
| enumerate_impl<Container&> enumerate(Container &c) { | |
| return {c}; | |
| } | |
| template <typename Container> enumerate_impl<Container> enumerate(Container &&c) { | |
| return {c}; | |
| } | |
| int main() { | |
| for (auto &&iv : enumerate(std::vector<int>{2, 3, 5, 7, 11, 13, 17})) { | |
| std::cout << std::get<0>(iv) << ' ' << std::get<1>(iv) << '\n'; | |
| } | |
| std::vector<int> x(10); | |
| for (auto &&iv : enumerate(x)) { | |
| std::get<1>(iv) = std::get<0>(iv); | |
| } | |
| std::cout << x[5] << '\n'; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment