Coders Packet

Vector in C++ Standard Template Library (STL)

By Rahul Chandrakant Suthar

In this tutorial, we will learn about vectors and their functions in C++ programming.

Vectors are utilized in C++ to store elements of comparable data types. However, unlike arrays, vectors can grow in size dynamically.

This means you'll be able to resize the vector while the program is running to fit your needs.

The C++ Standard Template Library includes vectors.

To use vectors, you want to include the vector header files in your program.

When to Use a Vector?

A C++ vector should be used when:

  • When dealing with constantly changing data elements.
  • If you don't know the size of your data before you start, vectors don't require you to set a maximum container size.

Vector declaration in C++

After including the header file, here's the way to declare a vector in C++:

vector variable_name;

The indicates the vector type. Primitive data types like int, char, and float may be used. As an example,

vector n;

Here, n is the name of the vector.

Notice that we didn't specify the size of the vector during the declaration. This is because the vector size can grow dynamically and does not need to be defined.




using namespace std;

int main() {
  vector < int > v;
  for (int j = 0; j < 10; j++) {
    v.push_back(j); //inserting elements in the vector

  cout << "the elements in the vector: ";
  for (auto it = v.begin(); it != v.end(); it++)
    cout << * it << " ";
  cout << "\nThe front element of the vector: " << v.front();
  cout << "\nThe last element of the vector: " << v.back();
  cout << "\nThe size of the vector: " << v.size();
  cout << "\nDeleting element from the end: " << v[v.size() - 1];
  cout << "\nPrinting the vector after removing the last element:" << endl;
  for (int i = 0; i < v.size(); i++)
    cout << v[i] << " ";
  cout << "\nInserting 5 at the beginning:" << endl;
  v.insert(v.begin(), 5);
  cout << "The first element is: " << v[0] << endl;
  cout << "Erasing the first element" << endl;
  cout << "Now the first element is: " << v[0] << endl;
  if (v.empty())
    cout << "\nvector is empty";
    cout << "\nvector is not empty" << endl;

  cout << "Size of the vector after clearing the vector: " << v.size();






Download Complete Code


No comments yet

Download Packet

Reviews Report

Submitted by Rahul Chandrakant Suthar (Rahulcs27)

Download packets of source code on Coders Packet