Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How stl vector gives random access

Tags:

c++

stl

stdvector

Yesterday evening I was using std::vector for my work, and this question popped into my mind: how does vector gives random access?

I tried to look into code but was unsuccessful. Can anyone give some pointers?

Thanks, Arun

like image 737
Arun Chhetri Avatar asked Nov 11 '09 18:11

Arun Chhetri


People also ask

Is random access possible in vector?

All pointer types are also valid random-access iterators. It is to be noted that containers like vector, deque support random-access iterators.

How are vectors implemented in STL?

Vector is implemented as a dynamically allocated array. The memory for this array is allocated in the constructor. As more elements are inserted the array is dynamically increased in size. A constructor without parameter creates an array with a default size.

What is random access in vector C++?

A Random Access Iterator is an iterator that provides both increment and decrement (just like a Bidirectional Iterator), and that also provides constant-time methods for moving forward and backward in arbitrary-sized steps.

How does std::vector work internally?

std::vector is a collection class in the Standard Template Library. Putting objects into a vector , taking them out, or the vector performing a resize when an item is added to a full vector all require that the class of the object support an assignment operator, a copy constructor, and move semantics.


3 Answers

Vector uses contiguous memory underneath, so it gives random access the same way as an array essentially: it knows the starting address and the size of elements and does some pointer math.

like image 178
i_am_jorf Avatar answered Nov 09 '22 10:11

i_am_jorf


Sure, here are some pointers:

int *x, *y;

But seriously, a vector is internally just implemented as an array. It provides an overloaded indexing operator ([]) to allow you to access it like an array.

like image 25
Thomas Avatar answered Nov 09 '22 10:11

Thomas


at least a factor of two

Actually, many implementations use a factor of 1.5 The important thing is that it's a factor, so you get exponential vector growth.

like image 29
Fred Avatar answered Nov 09 '22 08:11

Fred