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.

[showads ad=inside_post]

Lets see an example,

#include <iostream>
#include <vector>
int main()
{
   // This is a vector of int
    std::vector<int> vecOfInts;

    // While Adding it automatically adjusts it's size
    for(int i = 0; i < 10; i++)
        vecOfInts.push_back(i);

    std::vector<int>::iterator it = vecOfInts.begin();
    while(it != vecOfInts.end())
    {
        std::cout<<*it<<" , ";
        it++;
    }

    std::cout<<std::endl;

    for(int i = 0; i < vecOfInts.size(); i++)
        std::cout<<vecOfInts[i]<<" , ";

    std::cout<<std::endl;

    return 0;
}

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.

3.) Performance:
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.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top