Vectors are STL containers that are used to store data dynamically. They are also considered as the dynamic representation of arrays, with the ability to increase or decrease their size automatically depending on the insertion and deletion of the elements. Just like its static counterpart, it can store only a single entity on a single index. Both the processes of insertion and deletion take place from the last index to the first index. While deletion takes a constant time, inserting an element can take differential time since the vector has to resize itself after the addition of the element.

Just like other STL containers, the vector class also provides you with various member functions. These functions are part of three subcategories:

  • Iterators
  • Capacity
  • Modifiers

1. Iterators: Iterator functions are those functions that allow you to iterate or move through a vector container. The following are the types of iterators provided by a C++ vector: 

begin(), end(), rbegin(), rend(), cbegin(), cend(), crbegin(), crend().

2. Capacity:  These member functions of the C++ vector deal with the size and capacity of a vector container. The following are the types of capacity provided by C++ vector:

 size(), max_size(), capacity(), resize(n), empty(), shrink_to_fit(), reserve().

3. Modifiers: Modifier functions are the functions that modify a vector container such as removing an element, deleting, and so on. The following are the types of modifiers provided by C++ vector:

assign(), push_back(), pop_back(), insert(), erase(), swap(), clear(), emplace(), emplace_back().

Syntax 

The syntax to declare a vector in C++ is:

vector <type> vector_name(size)

Description of the syntax

  • Keyword “vector”: The keyword “vector” is provided at the beginning to declare a vector in C++.
  • type: This parameter is the data type of the elements that are going to be stored in the vector.
  • vector_name: This is the user-specified variable name of the vector.
  • size: This is an optional parameter that specifies the size of the vector. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Examples of Vectors

The following program checks if the vector contains a duplicate element. And it returns true if it contains the duplicate element, otherwise, it returns false.

#include<bits/stdc++.h>

using namespace std;

//function to check if the vector 

//contains a duplicate element or not

bool containsDuplicate(vector<int>& nums)

{

    //check if the vector is empty

    if(nums.empty())

        return false; 

    //sort the vector

    sort(nums.begin(), nums.end());

    int i = 0;

    int j = i+1;

    while(j<nums.size())

    {

        //check if the current element 

        //is not equal to its successor

        if(nums[i] != nums[j])

        {

            i++;

            j++;

        }

        else

            return true;

    }

    return false;

}        

int main()

{

    vector<int> nums{ 2, 3, 5, 1, 2, 4 };

    //print vector elements

    cout <<"Vector elements are ";

    for (int x : nums)

        cout << x << " ";

    cout <<endl;

    //print result

    if(containsDuplicate(nums))

        cout <<"Vector contains a duplicate element";

    else

        cout <<"Vector does not contain a duplicate element";

}

Initialize_Vector_In_C_Plus_Plus_1 

In the program depicted above, the duplicate function checks for duplicate elements in the vector. The function returns false if the vector is empty since an empty vector can not contain a duplicate element. If the element is non-empty, you need to sort the vector so that all the duplicates get reordered in correspondence to their originals. After that, you need to iterate the vector to check if two successive elements are equal. If it is so, the function returns true, otherwise, you get false as the return statement.

Also Read: C++ Functions: Syntax, Types and Call Methods

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Initializing a Vector in C++ 

The vector in C++ stores the reference of the objects and not the data directly. These objects can be of any data type like integer, char, string, etc. Unlike static containers like an array, a vector does not need a size to be initialized with. You can initialize a vector without defining the size of the container since it can increase as well as decrease its size dynamically.

You can initialize a vector in 6 different ways and now you will explore all these ways in detail in the next section. These 6 ways are:

  • Using the push_back() method to push values into the vector.
  • Using the overloaded constructor.
  • Passing an array to the vector constructor. 
  • Using an existing array.
  • Using an existing vector.
  • Using the fill() method.

Also Read: Introduction to Classes And Objects in C++

Ways to Initialize a Vector in C++ 

The following different ways can be used to initialize vector in C++:

  • Using the push_back() Method to Push Values Into the Vector

The push_back() method of the class vector is used to push or insert elements into a vector. It inserts each new element at the end of the vector and the vector size is increased by 1. 

Syntax

vector_name.push_back(data)

vector_name is the name of the vector. The push_back() method accepts one element and inserts it at the end of the vector.

Example

Consider a vector v1.

Input:  v1.push_back(100)

v1.push_back(200)

v1.push_back(300)

Output: Resulting vector is:

  100 200 300 with size 3.

Input:  v1.push_back(1)

v1.push_back(2)

Output: Resulting vector is:

  100 200 300 1 2 with size 5.

The following program illustrates how to initialize a vector in C++ using the push_back() method:

#include <iostream>

#include <vector>

using namespace std;

int main() {

  // declare a vector

  vector<int> v1;  

  // initialize vector using push_back()  

  v1.push_back(100); 

  v1.push_back(200); 

  v1.push_back(300);

  v1.push_back(1); 

  v1.push_back(2); 

  cout << "The elements in the vector are:\n"; 

  // traverse vector

  for (int i = 0; i < v1.size(); i++)

  {

    // print the vector elements

    cout << v1[i] << " "; 

  }

  return 0; 

}

Initialize_Vector_In_C_Plus_Plus_2

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Steps

  1. Declare a vector v1.
  2. Initialize the vector using the push_back() method. Insert vector elements one by one
  3. Traverse the vector
  4. Print the vector elements
  • Using the Overloaded Constructor

The overloaded constructor can also be used to initialize vectors in C++. This constructor accepts two parameters. The size of the vector and the value to be inserted is provided while initializing the vector. The value provided will be inserted into the vector multiple times (equal to the provided size of the vector).

Syntax

vector<type> vector_name(size, data)

The parameter size is the number of elements to be inserted into the vector (or simply the size of the vector) and the data is the value to be inserted.

Also Read: Constructor in C++: A Comprehensive Guide to Constructor

Example

Input: vector<int> v1(5, 2)

Output: The resulting vector will be:

  2 2 2 2 2

Input: vector<int> v2(4, 1)

Output: The resulting vector will be:

  1 1 1 1

The following program illustrates how to initialize a vector in C++ using the overloaded constructor:

#include <iostream>  

#include <vector>  

using namespace std;  

int main()  

 {  

  // initialize size 

  int size = 5;  

  // initialize vector using overloaded constructor 

  vector<int> v1(size, 2);   

  // print the vector elements

  cout << "The vector v1 is: \n";

  for (int i = 0; i < v1.size(); i++)  

  {  

    cout << v1[i] << " ";   

  }   

  cout << "\n"; 

  // initialize vector v2 

  vector<int> v2(4, 1);    

  // print elements of vector v2

  cout << "\nThe vector v2 is: \n";

  for (int i = 0; i < v2.size(); i++)  

  {  

    cout << v2[i] << " ";   

  }   

  cout << "\n\n";

  return 0;  

Initialize_Vector_In_C_Plus_Plus_3.

Steps

  1. Initialize the size of the vector
  2. Initialize the vector using the overloaded constructor by specifying the size and the value to be inserted
  3. Traverse the vector
  4. Print the vector elements
  • Passing an Array to the Vector Constructor

Another way to initialize a vector in C++ is to pass an array of elements to the vector class constructor. The array elements will be inserted into the vector in the same order, and the size of the vector will be adjusted automatically.

Syntax

vector<type> vector_name{array of elements}

You pass the array of elements to the vector at the time of initialization.  

Example

Input: vector<int> v1{10, 20, 30, 40, 50}

Output: The resulting vector will be:

  10 20 30 40 50

Input: vector<char> v2{'a', 'b', 'c', 'd', 'e'}

Output: The resulting vector will be:

  a b c d e

The following program illustrates how to initialize a vector in C++ by passing an array to the vector class constructor:

#include <iostream>  

#include <vector>  

using namespace std;  

int main()  

 {   

  // pass an array of integers to initialize the vector 

  vector<int> v1{10, 20, 30, 40, 50};

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v1.size(); i++)  

  {  

    cout << v1[i] << " ";   

  }

  cout << "\n\n"; 

  // pass an array of characters to initialize the vector  

  vector<char> v2{'a', 'b', 'c', 'd', 'e'}; 

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v2.size(); i++)  

  {  

    cout << v2[i] << " ";   

  }   

  cout << "\n\n"; 

  return 0;  

}  

Initialize_Vector_In_C_Plus_Plus_4.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Steps

  1. Declare a vector
  2. Initialize the vector. Pass an array of elements to the vector class constructor
  3. Traverse the vector
  4. Print the vector elements
  • Using an Existing Array

This is one of the most standard ways to initialize vectors in C++ elegantly. You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class.

Also Read: Iterators in C++: An Ultimate Guide to Iterators

Syntax

data_type array_name[n] = {1,2,3};

vector<data_type> vector_name(arr, arr + n)

The array of size n is passed to the iterator constructor of the vector class. 

Example

Input:   int a1[5] = {10, 20, 30, 40, 50}

      vector<int> v1(a1, a1 + 5)

Output: The resulting vector will be:

  10 20 30 40 50

Input:  char a2[5] = {'a', 'b', 'c', 'd', 'e'}

   vector<int> v2(a2, a2 + 5)

Output: The resulting vector will be:

  a b c d e

The following program illustrates how to pass an existing array to the iterator constructor of the vector class to initialize a vector in C++:

#include <iostream>  

#include <vector>  

using namespace std;  

int main()  

 { 

  // initialize an array of integers

  int a1[5] = {10, 20, 30, 40, 50};

  // initialize vector

  vector<int> v1(a1, a1 + 5); 

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v1.size(); i++)  

  {  

    cout << v1[i] << " ";   

  }

  cout << "\n\n"; 

  // initialize an array of char

  char a2[5] = {'a', 'b', 'c', 'd', 'e'};

  vector<int> v2(a2, a2 + 5);

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v2.size(); i++)  

  {  

    cout << v2[i] << " ";   

  }   

  cout << "\n\n";

  return 0;   

}  

Initialize_Vector_In_C_Plus_Plus_5.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Steps

  1. Initialize an array
  2. Pass the array to the iterator constructor of the vector class to initialize the vector
  3. Traverse the vector
  4. Print the vector elements
  • Using an Existing Vector

The range constructor of the vector class can also be used to initialize a vector. You pass the iterators of an existing vector to the constructor to specify the range of the elements to be inserted into the new vector.

Syntax

vector<type> vector_name(iterator_first, iterator_last)

Here, you must pass the iterators pointing to the existing vector to the constructor, to initialize the new vector. The elements lying in the range that is passed as arguments are inserted into the new vector.

Example

Input:  vector<int> v1{10, 20, 30, 40, 50};

   vector<int> v2(v1.begin(), v1.end())

Output: The resulting vector will be:

  10 20 30 40 50

Input:  vector<int> v1{10, 20, 30, 40, 50};

  vector<int> v2(v1.begin(), v1.begin() + 3)

Output: The resulting vector will be:

  10 20 30 

The following program illustrates how to initialize a vector in C++ using an existing vector:

#include <iostream>  

#include <vector>  

using namespace std;  

int main()  

 { 

  // initialize a vector

  vector<int> v1{10, 20, 30, 40, 50};

  // initialize vectors using the range constructor

  vector<int> v2(v1.begin(), v1.end());

  vector<int> v3(v1.begin(), v1.begin() + 3);

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v2.size(); i++)  

  {  

    cout << v2[i] << " ";   

  }

  cout << "\n\n";

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v3.size(); i++)  

  {  

    cout << v3[i] << " ";   

  }  

  cout << "\n\n";

  return 0;  

}  

Initialize_Vector_In_C_Plus_Plus_6

Steps

  1. Initialize a vector using any of the methods discussed above
  2. Pass the iterators of this vector (specifying the range) to the range constructor of the new vector
  3. Traverse the vector
  4. Print the vector elements
  • Using the fill() Method

The fill() function, as the name suggests, fills or assigns all the elements in the specified range to the specified value. This method can also be used to initialize vectors in C++.

Syntax

fill(begin, end, value)

The fill() function accepts three parameters begin and end iterators of the range and the value to be filled. The iterator begin is included in the range whereas the iterator end is not included.

Example

Consider vectors v1 and v2 of size 5.

Input:  fill(v1.begin(), v1.end(), 6)

Output: The resulting vector will be:

  6 6 6 6 6

Input:  fill(v2.begin() + 2, v2.begin() + 4, 6)

Output: The resulting vector will be:

  0 0 6 6 0

The following program illustrates how to initialize a vector in C++ using the fill() function:

#include <iostream>  

#include <vector>  

using namespace std;  

int main()  

 { 

  // declare a vector

  vector<int> v1(5);

  // initialize the vector using the fill() method

  fill(v1.begin(), v1.end(), 6);

  // declare another vector

  vector<int> v2(5);

  // initialize v2

  fill(v2.begin() + 2, v2.begin() + 4, 6);

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v1.size(); i++)  

  {  

    cout << v1[i] << " ";   

  }

  cout << "\n\n"; 

  // print vector elements

  cout << "The vector elements are: \n";

  for (int i = 0; i < v2.size(); i++)  

  {  

    cout << v2[i] << " ";   

  }  

  cout << "\n\n";

  return 0;   

}  

Initialize_Vector_In_C_Plus_Plus_7

Steps

  1. Declare a vector
  2. Pass the range and the value to the fill() function to initialize the vector
  3. Traverse the vector
  4. Print the vector elements
Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!

Final Thoughts!

This article walked you through the ins and outs of vectors in c++ and how to initialize them. You looked at some common examples of vectors and six different ways to initialize vectors. To name some of them, you can initialize vectors using the push_back() method, using an overloaded constructor, an existing array, or a vector, using the fill() method, etc. You looked at the steps and examples of all such methods to initialize vectors.

If you want to learn more about the basic concepts of the C++ programming language, you can check out Simplilearn’s guide on C++ Programming for Beginners.

You can also get a complete overview of the technologies used in full-stack software development through our course on Post Graduate Program in Full Stack Web Development. This course is taught by industry experts and it will walk you through some of the most trending technologies such as DevOps, Agile, AWS, Java, HTML, etc.

You should also check out some of our carefully crafted free online courses.

If you have any queries or suggestions for us, please mention them in the comment box and our experts will answer them for you as soon as possible.

Happy Learning!