Summary: In this tutorial, we will learn what vector is in C++ and how can we use it in our C++ program.

Introduction to Vector

A vector in C++ is a container like an array that can hold multiple values of the same data type but is dynamic.

It can easily grow and shrink at execution time and treated as an object in C++.

Its syntax is similar to an array but has additional inbuilt functions such as sort, reverse, move, find, etc. that make it more powerful.

In short, the vector is more efficient and useful than an array when it comes to managing multiple data of the same type.

How to Declare Vector?

We can define a vector in C++ in many different ways, but for that, we have to include the vector header file first.

Method 1: When the size and data type is unknown:

Method 2: When the size is known at the time of declaration:

Method 3: When the values prior to the declaration is known:

How to Access Vector Element?

Accessing the vector element is similar to accessing the array element i.e. using the subscript operator ([]):

We can also use its inbuilt at() method to access its elements:

Basic Vector Methods

These are some of the inbuilt methods we can use with vectors in C++:

Use: vector_name.method_name();

  • push_back(x) – Insert ‘x’ at the back of the vector.
  • pop_back() – Removes last element from the vector.
  • clear() – Removes all elements from the vector.
  • back() – Return last element in the vector.
  • front() – Return first element in the vector.
  • capacity() – Size of the vector.
  • size() – Size of the vector.
  • assign(n,x) – Fills vector with ‘n’ numbers of ‘x’.

C++ Example using Vector Methods

Output:

Initial Vector Elements
2 8 4 1
first element: 2
last element: 1
Elements after Appending 10:
2 8 4 1 10
Elements after Poping last element:
2 8 4 1
Size of the Vector: 4

In this programming tutorial, we learned with examples about vector in C++.

Leave a Reply

eighteen − 15 =