0

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?

Andrew
  • 626
  • 6
  • 16
  • 1
    `ranges` library doesn't have `action`, that's the [`range-v3`](https://github.com/ericniebler/range-v3) by ericniebler. – Ranoiaetep Jun 19 '21 at 00:17
  • Also `tmp.push_back(99.99);` seems to work fine for me: https://godbolt.org/z/v4Ycx6TxP – Ranoiaetep Jun 19 '21 at 00:18
  • Also, if you want to create a `vector` from a range view, you can simply do `auto vec = std::vector(std::ranges::rbegin(vi), std::ranges::rend(vi));` – Ranoiaetep Jun 19 '21 at 00:20

1 Answers1

2

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I've figured out why the ```tmp.push_back(99.99)``` didn't work for me! In reality, I'm using a complex type for ```tmp``` and was trying to push a double to that so there was a type conflict!! However, thanks for suggesting the vector constructor method as I wasn't aware of that and it seems the simplest method. – Andrew Jun 19 '21 at 06:22