Last active
December 2, 2020 22:24
-
-
Save christianparpart/83af24a2706e0a56be17734a706a91ff to your computer and use it in GitHub Desktop.
C++ helper to extract nth element from a range in a loop.
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
#pragma once | |
#include <utility> | |
#include <iterator> | |
template <int N, typename Range> | |
class nth_range { | |
public: | |
using RangeIterator = decltype(std::begin(std::declval<Range>())); | |
constexpr explicit nth_range(Range& _range) noexcept : begin_{std::begin(_range)}, end_{std::end(_range)} {} | |
struct iterator { | |
RangeIterator current; | |
constexpr auto& operator*() const noexcept { return std::get<N>(*current); }; | |
constexpr auto& operator++() noexcept { ++current; return *current; }; | |
constexpr auto& operator++(int) noexcept { ++current; return *current; }; | |
constexpr bool operator==(iterator const& _other) const noexcept { return current == _other.current; } | |
constexpr bool operator!=(iterator const& _other) const noexcept { return !(*this == _other); } | |
}; | |
constexpr auto begin() const { return iterator{begin_}; } | |
constexpr auto end() const { return iterator{end_}; } | |
private: | |
RangeIterator const begin_; | |
RangeIterator const end_; | |
}; | |
template <std::size_t N, typename Range> | |
auto nth(Range& _range) { return nth_range<N, Range>(_range); } |
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 "nth.h" | |
#include <iostream> | |
#include <utility> | |
#include <vector> | |
int main() | |
{ | |
using namespace std; | |
auto vec = vector<pair<int, char>{{1, 'a'}, {2, 'b'}}; | |
for (auto const v : nth<1>(vec)) | |
cout << v << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment