Andrew
Andrew

Reputation: 658

C++20 ranges reverse view problem in VS2019 (latest)

I'm trying to read a vector in the reverse order using a ranges::subrange view but I'm confused about how it should work. I'm aware of ranges::reverse but I'm trying to avoid using this method as a personal preference and learning experience.

My non-working example code is here:

#include <algorithm>
#include <ranges>
#include <vector>
#include <iostream>

int main() {
    using namespace std::ranges;

    std::vector<int> v {1, 2, 3, 4};
    
    const auto [first, last] = range(v.rbegin(), v.rend());

    auto view = subrange(first, last - 1);

    for (auto n : view) {
        std::cout << n << ' ';
    }
}

This is how I imagine it should work but clearly, there is a distance between my imagination and reality. In some examples online I've seen ranges::equal_range being used to set the [first, last] iterators but I'm not interested in matching any values, just setting the iterators to rbegin and rend.

What ranges command should I be using to define the [first, last] iterators or how should I be using the range command correctly?

Upvotes: 0

Views: 1877

Answers (1)

Barry
Barry

Reputation: 302748

Given that you want 4,3,2, you're looking for:

v | views::drop(1) | views::reverse

That is, drop the first element (the 1), and then reverse the remainder.


If you really want to avoid the range adapters, you could do:

subrange(v.rbegin(), v.rend() - 1)

to accomplish the same thing. All subrange does is combine two iterators (or an iterator and a sentinel) together into a range.


Demo of both.

Upvotes: 4

Related Questions