C++ std::vector example and why should I use std::vector?
Vector is a template based container that behaves just like a Dynamic Array.
It can expands its memory at run time and always store elements in contiguous memory location just like Array.
We can store any type of element in vector by specifying the type as template argument.
Lets see an example,
// This is a vector of int
// While Adding it automatically adjusts it's size
for(int i = 0; i < 10; i++)
std::vector<int>::iterator it = vecOfInts.begin();
while(it != vecOfInts.end())
std::cout<<*it<<" , ";
for(int i = 0; i < vecOfInts.size(); i++)
std::cout<<vecOfInts[i]<<" , ";
Important Points about std::vector :
1.) Ordered Collection:
In std::vector all elements will remain in same order in which they are inserted.
2.) Provides random access:
Indexing is very fast in std::vector using opeartor , just like arrays.
It Performs better if insertion and deletion is in end only and gives worst performance if insertion/deletion is at middle or at starting of vector.
4.) Contains Copy:
It always stores copy of the object not the same reference. So, if you are adding objects of user defined classes the you should define copy constructor and assignment opeartor in you class.
Why Should I use std::vector ?
std::vector give same kind of fast performance in indexing and iterations as arrays. But it dont have a Fixed Size limitaton like Arrays. You dont need to provide the fixed size for std::vector in advance. Just start inserting elements in std::vector and it will automatically expand its size.