×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Vectors in C++ Standard Template Library (STL)

By Abhishek Jain Last updated : December 11, 2023

Vectors in C++ STL

Vector is the most useful container in the STL. All the STL containers are useful, but you'll find yourself reaching for vector more often than other. Vectors are designed to replace most applications of arrays and arrays are so useful, they've been included in every commercially successful programming language.

Vectors serve you better than arrays when memory required is undefined at the time of dynamic memory allocation. Vectors are capable to increase its size at runtime (reallocation). It consumes extra space to efficiently store and increase its size dynamically.

Their memory grows as elements are added to these containers, and when a vector is destroyed, its destructor automatically destroys the elements in the container and de-allocates the memory holding those elements.

Declaring a vector

Below is the syntax to declare a vector:

vector<type> vector_name;

C++ STL Vector Functions

Some useful member functions of vectors:

  1. push_back(): This function add a new element at the end of vector after its current last element.
  2. pop_back(): This function removes the last element from the vector.
  3. begin(): It returns a iterator pointing to the first element of the vector.
  4. end(): It returns a iterator pointing to the last elements of the vector.
  5. size(): This function returns the size(number of elements) of the vector.
  6. clear(): It removes all the elements of the vector, making it empty with size 0.

Example of C++ STL Vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
  int i, k;
  //vector declaration
  vector <int> v;

  //printing size before insertion
  cout << "Before Insertion:" << v.size() << endl;

  //input elements
  cout << "Enter Elements:";
  for (int i = 1; i < 5; i++) {
    cin >> k;
    v.push_back(k);
  }

  cout << "Size after Push_back():" << v.size() << endl;
  v.pop_back();

  cout << "Size after Pop_back():" << v.size() << endl;
  cout << "Elements Present in vector are:";
  for (vector <int> ::iterator j = v.begin(); j != v.end(); j++)
    cout << * j << " ";
  cout << endl;

  //clearing vector
  v.clear();
  cout << "After clear():" << v.size() << endl;

  return 0;
}

Output

Before Insertion:0
Enter Elements:4 86 23 1
Size after Push_back():4
Size after Pop_back():3
Elements Present in vector are:4 86 23
After clear():0

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.