Vector is a container in C++ Standard Template Library (STL). It is similar to an array that can grow and shrink at execution time.

Vector in C++:

  • Provides similar techninques and syntax as arrays.
  • Is powerful and inbuilt functions like sort, reverse, move, find etc to make task more easy.
  • Also provides method to check its bounds.
  • More efficient than array.
  • Indexing is similar to the array i.e 0 to n-1

Declare Vector in C++

A vector can be declared in several different ways, but the important point is, that its declaration is slightly different from array declaration because vector is an object.

To declare vector we must include ‘vector’ library and use namespace ‘std’ because vector type is a part of a standard library.

To explicitly tell the size of the vector at the time of deceleration.

To initialize the vector with values at the time of declaration.

Access vector Element

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

Another way to access vector element is using at() method.

Basic Vector Methods

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


vector in C++

If you have any doubt then comment below.

Leave a Reply