Andrew
Andrew

Reputation: 658

C++20 ranges - how to modify a range?

I have a vector defined as:

auto xs = std::vector<double>(5) = { 1.0, 2.0, 3.0, 4.0, 5.0 };

and I've created a view on this vector:

auto vi = xs | std::ranges::views::drop(1);

for example. However, I'd like to convert the view data into an actionable range or another vector so that I can modify it.

So far, I've tried this:

#include <ranges>
#include <algorithm>

auto tmp = std::vector<double>();
std::ranges::copy_n(std::ranges::rbegin(vi), std::ranges::size(vi) - 1, std::back_inserter(tmp));
std::ranges::action::push_back(tmp, 99.99);

but the push_back action isn't recognised. Am I missing a header, if so, which one or isn't this implemented in C++20?

I've also tried:

tmp.push_back(99.99);

but this doesn't work either.

I'd like to stick to the C++20 implementation rather than use the ranges library and the type of tmp can be something completely different, such as another type or action/range.

What's the best/most efficient way of doing this, please?

Upvotes: 0

Views: 932

Answers (1)

eerorika
eerorika

Reputation: 238491

However, I'd like to convert the view data into ... another vector so that I can modify it.

You can use the constructor of std::vector that accepts a pair of iterators:

template< class InputIt >
constexpr vector( InputIt first, InputIt last,
                  const Allocator& alloc = Allocator() );

std::ranges::action::push_back(tmp, 99.99);

but the push_back action isn't recognised. Am I missing a header, if so, which one or isn't this implemented in C++20?

The standard library doesn't have ranges::actions. You can use member functions instead:

tmp.push_back(99.99);

I've also tried:

tmp.push_back(99.99);

but this doesn't work either.

I see no reason why that wouldn't work. I recommend thinking about what you were expecting it to do and why you expect that.

Upvotes: 2

Related Questions