[cfe-dev] C++11 reverse iterators (was C++11 is here)
Howard Hinnant
howard.hinnant at gmail.com
Tue Mar 4 15:43:52 PST 2014
On Mar 4, 2014, at 6:11 PM, Chris Lattner <sabre at nondot.org> wrote:
> Sure, it won't be as nice as Python, but in my limited experience with C++'11 foreach loops, the #1 reason I can't use them is because there is no way to parallel iterate two vectors (as a random example) which would be simple if an index were available. It doesn't matter to me how syntactically convenient it is to get the index, so long as it is possible.
Thrown together…
#include <cstddef>
class index_range
{
std::size_t begin_;
std::size_t end_;
public:
class const_iterator
{
std::size_t i_;
public:
explicit constexpr const_iterator(std::size_t i) noexcept : i_(i) {}
constexpr std::size_t operator*() const noexcept {return i_;}
const_iterator& operator++() noexcept {++i_; return *this;}
friend constexpr bool operator==(const_iterator x, const_iterator y) noexcept
{return x.i_ == y.i_;}
friend constexpr bool operator!=(const_iterator x, const_iterator y) noexcept
{return !(x == y);}
};
constexpr index_range(std::size_t begin, std::size_t end) noexcept
: begin_(begin)
, end_(end)
{}
constexpr const_iterator begin() const noexcept {return const_iterator(begin_);}
constexpr const_iterator end() const noexcept {return const_iterator(end_);}
};
#include <vector>
#include <cassert>
int
main()
{
std::vector<int> v1(3);
std::vector<int> v2 = v1;
assert(v1.size() == v2.size());
for (auto i : index_range(0, v1.size()))
{
v1[i] = i;
v2[i] = i;
}
assert(v1 == std::vector<int>({0, 1, 2}));
assert(v2 == std::vector<int>({0, 1, 2}));
}
Admittedly, you don’t want to write index_range every time you want to form such a loop. But if it were a easily available utility…
Howard
More information about the cfe-dev
mailing list