Simplest way to assign std::span to std::vector
Asked Answered
E

4

14

I wanted to do this

#include <vector>
#include <span>

struct S
{
    std::vector<int> v;
    void set(std::span<int> _v)
    {
        v = _v;
    }
};

But it does not compile. What are the alternatives?

Ehrman answered 1/9, 2020 at 10:46 Comment(0)
E
23
v.assign(_v.begin(), _v.end());
Echidna answered 1/9, 2020 at 10:49 Comment(3)
Thanks, pretty neat. I was thinking of doing clear() + insert() but this looks better.Ehrman
that (clear + insert) is basically what assign does.Julissajulita
admittedly the clear is extra if its in the constructor as you wouldn't expect the any data elements in an empty vector.Gangrene
M
4

You can also use the std::vector::insert as follows:

v.insert(v.begin(), _v.begin(), _v.end());

Note that, if the v should be emptied before, you should call v.clear() before this. However, this allows you to add the span to a specified location in the v.

(See a demo)

Mistiemistime answered 1/9, 2020 at 12:26 Comment(0)
R
4

Use std::vector<T,Allocator>::assign_range (C++23).

v.assign_range(_v);

// or “v.assign(_v.begin(), _v.end());”
Rehabilitate answered 13/2, 2024 at 6:11 Comment(0)
R
3

The general way to create a new container from any input range is std::ranges::to():

        v = _v | std::ranges::to<decltype(v)>();

This is more useful for passing a temporary to a function that's more constrained (e.g. it needs a sized or bidirectional range), but it can be used for assignment, too (at a short-term cost in memory, since v's contents are not released until after the new container is constructed).

Runkle answered 13/2, 2024 at 8:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.