Open In App

How to Declare a Vector in C++?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the vector is a dynamic array that can resize itself automatically to accommodate new elements. In this article, we will learn how to declare a vector in C++.

Declare a Vector in C++

In C++, vectors are defined as the class templates in <vector> header file. So, to declare a std::vector in C++, we first need to include the <vector> header. Then, we can declare a vector variable or object or instance using the below syntax

Syntax to Declare Vector in C++

vector<dataType> vector_Name;

Here,

  • vector_name: name of the instance.
  • dataType: type of each element of the vector.

The above vector will be constructed using the default constructor. We can also create a vector with different constructors as shown here.

C++ Program to Declare a Vector

The following program illustrates how we can declare a vector in C++:

C++
// C++ Program to illustrates how we can declare a vector
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Declare a vector of integers
    vector<int> vec = { 1, 2, 3, 4, 5 };

    // Print the elemetns of the vector
    cout << "Vector Elements: ";
    for (int number : vec) {
        cout << number << " ";
    }
    cout << endl;
    return 0;
}

Output
Vector Elements: 1 2 3 4 5 

Time Complexity: O(N) where N is the size of the vector.
Auxiliary Space: O(N)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads