Skip to content

Instantly share code, notes, and snippets.

@christianparpart
Last active December 2, 2020 22:24
Show Gist options
  • Save christianparpart/83af24a2706e0a56be17734a706a91ff to your computer and use it in GitHub Desktop.
Save christianparpart/83af24a2706e0a56be17734a706a91ff to your computer and use it in GitHub Desktop.
C++ helper to extract nth element from a range in a loop.
#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); }
#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