I have some questions about vector in STL to clarify.....
Where are the objects in vector allocated? heap?
does vector have boundary check? If the index out of the boundary, what error will happen?
Why array is faster than vector?
Is there any case in which vector is not applicable but array is a must?
1) std::vector is a sequence container that encapsulates dynamic size arrays.
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.
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.
vector<int>
allocates memory the same way new int[x]
would.at
method. It throws an std::out_of_range
exception if the boundary check fails. The operator[]
doesn't perform bounds checking.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With