Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::vector use an offset?

Tags:

c++

vector

Simple question really. When adding to or removing from the front of a vector, why do you need to shift all the elements to accommodate this change? Using an offset instead to modify the index given when indexing into the vector would solve this problem. Granted this could result in (at most) 2 contiguous blocks of data in memory but this seems like a small price to pay to reduce a linear operation to constant time.

Here's an example to be as clear as possible:

['A', 'B', 'C', _, _, _, _, _] offset is 0, 4th through 8th position unused.
push_front('M')
['A', 'B', 'C, _, _, _, _, 'M'] offset is -1

and then when indexing

operator[](size_t index) {
    return backing_array[(index + offset) % size]
}

I get this means there might not be one pure contiguous block of data but moving from 1 to 2 doesn't seem like a huge deal in exchange for constant time push and pop front.

like image 902
Keltek Avatar asked Nov 30 '22 09:11

Keltek


1 Answers

I get this means there might not be one pure contiguous block of data

No, that's the end of the story right there. The whole point of vector is that it is a "pure contiguous block of data". That's a fundamental requirement of the implementation.

The ability to do this is a core part of vector's entire purpose:

T *ptr = &vec[0];
ptr+1;
ptr == &vec[1];

Therefore, the interface cannot provide additional requirements that would prevent vector from being contiguous.

like image 170
Nicol Bolas Avatar answered Dec 05 '22 18:12

Nicol Bolas