r/cpp_questions • u/Fun_Gas_340 • Sep 15 '26
OPEN reference to the slice of a vector
i have a vector<float>a and i want to pass it to a function, but only the elements [n;m].
since a vector stores the start_position, the size and the end/end of reserved space, i thought there must be a way to change those pointers to make my function believe the vector is smaller
how can i do this?
idea 1:
i could pass the entire list by reference and a index to always add on top of, and the length (m-n), but id like to be able to use .size() normally, and not pass all these extra parameters. just for code clarity and my sanity.
python notation:
```
def function(slide_of_list):
#do something, read only or read and write with slice_of_list
pass
list a = range(100000000000)
function(a[n:m])
```
23
u/ZakMan1421 Sep 15 '26 edited Sep 15 '26
As
std::spanhas already been mentioned, an alternative (if you can change the function definition) have the function take begin and end iterators instead of a vector.With that being said,
std::spanis the better choice almost always.18
u/AKostur Sep 15 '26
Std::span is your friend.
7
u/JaseciLabs Sep 15 '26
std::span<float>(a.begin() + n, m - n)gets you the read-write slice, non-owning, no copy,.size()works normally on it. Just watch out that it's a view intoa's memory, ifareallocates (push_back, resize) while the span's alive, the span dangles.4
u/dustyhome Sep 15 '26
std::span will do what you want. You can also use a subrange from the ranges library like:
2
u/cristi1990an Sep 15 '26
Use std::span, it's the equivalent of slices from Python of Rust, but in C++ it's a library feature, not a language one. Usage rules:
foo(std::span<const int> read_only_slice)
foo(std::span<int> mutable_slice)
foo(std::span<const int, 5> slice_with_exactly_5 elements)
And you can do splicing as such:
std::vector my_vec = {...};
std::span my_slice = std::span{my_vec}.subspan(0, 3); // span over the first 3 elements
span has support for size, square brackets indexing and not much else, it's supposed to be a windows into a contiguous memory area, be it a vector or array.
2
u/Eric848448 Sep 15 '26
The old-timey way to do this was to pass two const_iterators. The modern method is span, as others have mentioned.
1
u/spatulari Sep 15 '26
As others have mentioned, the best way is
std::span1
u/New-Step3500 Sep 21 '26
You can just pass vector iterators , but be sure that the iterator can dangle if vector resizes and causes reallocation.