Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about Vector in STL

Tags:

c++

stl

vector

I have some questions about vector in STL to clarify.....

  1. Where are the objects in vector allocated? heap?

  2. does vector have boundary check? If the index out of the boundary, what error will happen?

  3. Why array is faster than vector?

  4. Is there any case in which vector is not applicable but array is a must?

like image 813
skydoor Avatar asked Mar 21 '10 21:03

skydoor


People also ask

What kind of container is the STL vector?

1) std::vector is a sequence container that encapsulates dynamic size arrays.

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 the difference between vector and list STL?

Vector may have a default size. List does not have default size. In vector, each element only requires the space for itself only. In list, each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.


1 Answers

  1. In a contiguous memory block on the heap. A vector<int> allocates memory the same way new int[x] would.
  2. Only if you use the at method. It throws an std::out_of_range exception if the boundary check fails. The operator[] doesn't perform bounds checking.
  3. Because an array gives direct access to memory, while accessing a vector element most likely involves a method call. The difference can be ridiculously small though, especially if your compiler decides to inline the calls.
  4. In general, you'll use a vector if you want your container to have a dynamic size, and a simple array if a known fixed size is enough. Be sure to check out the other containers, like deque and list, to be sure you pick the most appropriate one. Otherwise, if you need to deal with non-C++ APIs, you'll obviously need to have access to a regular array. (edit) @BillyONeal says you should use &vector[0] to get the address of the underlying array, but use it with care since it can change if the vector's capacity changes.
like image 189
zneak Avatar answered Oct 15 '22 06:10

zneak