Using std::vector – C++ std::vector Why Should I Use std::Vector with Example

Using std::vector: In the previous article, we have discussed about Object Oriented Approach to Display a sequence of numbers without any For-Loop or Recursion in CPP. Let us learn About std::vector Why Should I Use std::Vector in C++ Program.

Why Should I Use std::vector with Example in C++

In this article we will get to know about std::vector why to use it along with an example. So. let’s start.

What is vector ?

Vectors are sequence containers which are same as dynamic arrays as it can change it’s size automatically when an element is appended to it. As it is a sequence container so elements are arranged in a sequence/serial wise and it uses contiguous storage locations for storing the elements. Another thing is that any type of element can be stored just by by specifying the type as template argument. Actually it is a part of STL.

Points to remember about std::vector :

  1. Ordered Collection: Inserted elements remain in same order in which order they are inserted.
  2. Random access: Just like array, random access is possible using indexing through [].
  3. Performance: Better performance during insertion and deletion at end but worst performance if insertion and deletion at start or at middle.
  4. Contains Copy: It always stores copy of the object.

Why to use std::vector ?

  1. Provides fast performance in indexing and iterations as arrays.
  2. Don’t need to provide the fixed size for std::vector in advance as like array.
  3. Start inserting elements in std::vector as required and it will automatically resizes.

Example program to see the use of std::vector :

#include <iostream>
#include <vector>

int main()
{
   // vector of intigers
    std::vector<int> vector_ints;
    
    // automatically resizing during appending
    for(int j = 0; j < 5; j++)
        vector_ints.push_back(j);
    std::vector<int>::iterator it = vector_ints.begin();
    while(it != vector_ints.end())
    {
        std::cout<<*it<<" , ";
        it++;
    }
    std::cout<<std::endl;
    for(int i = 0; i < vector_ints.size(); i++)
        std::cout<<vector_ints[i]<<" , ";
    std::cout<<std::endl;
    return 0;
}
Output :

0 , 1 , 2 , 3 , 4 , 
0 , 1 , 2 , 3 , 4 ,