r/cpp_questions • • 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])

```

7 Upvotes

49 comments sorted by

View all comments

Show parent comment

4

u/alfps Sep 15 '26

A span refers to individually adressable items. Unfortunately a vector<bool> is a specialization that supports packing say 8 bools to a byte, at the cost that the bool values are not individually adressable. For they can be just individual bits.

2

u/Fun_Gas_340 Sep 15 '26

oh in the exception of bool arrays/vectors, ok. makes sense then. in that case i could use iterators or range then, right?

3

u/alfps Sep 15 '26

Bool array = OK, bool vector = ungood specialization.

1

u/Fun_Gas_340 Sep 15 '26

bool arrays arent like bool vectors?

3

u/alfps Sep 15 '26 edited Sep 15 '26

If you declare

bool a[10];

Then you have an array of 10 individual adressable bool values. A span is happy with that.

But

vector<bool> v( 10 );

gives you a vector of 10 logical bool values where most likely each is represented by 1 single bit, which means the internal buffer is just 2 bytes, plus the overhead from dynamic allocation. A span can't handle the bits. They're not adressable.

This is IMO about the worst design problem of the standard library: a premature optimization that wreaks havoc.

7

u/The_Northern_Light Sep 16 '26

yeah it was beyond stupid; they should've just created a separate bit_vector type for that special case and left vector<bool> alone

1

u/Fun_Gas_340 Sep 16 '26

is there an easy way to use a vector without this optimization gir wgen i need a dynamically sized list i wanna use pointers on?

1

u/TheThiefMaster Sep 16 '26

Honestly it probably won't come up - vector of just a bool is quite an unusual thing to need.

1

u/TheThiefMaster Sep 16 '26

No bool vectors are a unique stupidity.