Vector in C++ STL

A vector manages its elements in a dynamic array. It enables random access, which means that you can access each element directly with the corresponding index. Appending and removing elements at the end of the array is very fast. However, inserting an element in the middle or at the beginning of the array takes time because all the following elements have to be moved to make room for it while maintaining the order. A vector stores elements in contiguous memory locations.

Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program.

#include <vector>

Syntax:

std::vector<object_type> variable_name;

C++ Vector Initialization:

There are different ways to initialize a vector in C++.

Method 1:

// Initialize list
vector<int> vec1 = {1, 2, 3, 4, 5, 6};
// Uniform initialize
vector<int> vec2 {1, 2, 3, 4, 5, 6};

Method 2:

vector<int> vec3(5, 10); //Here, 5 is the size of the vector and 10 is the value

C++ Vector Iterators:

Vector iterators are used to point to the memory address of a vector element. In some ways, they act like pointers in C++.

Syntax:

vector<T>::iterator iteratorName;

For Example:

// iterator for int vector
vector<int>::iterator itr1;

// iterator for double vector
vector<double>::iterator itr2;

auto keyword:

 The auto keyword simplifies the syntax to a great extent. Apart from this, auto keyword dynamically determines the data type of the assigned value, much like Python programming language. The auto keyword helps in keeping the code clean and tidy. Let us see examples to understand it better.

auto iterator = itr;

Most used functions in Vector:

  • begin() – it returns an iterator pointing to the first element of the vector.
auto iterator = it;

it = v1.begin();
  • end() – it returns an iterator pointing to the element theoretically after the last element of the vector.
auto iterator = it;

it = v1.end();
  • rbegin() – it returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
auto iterator = itr;

itr = v1.rbegin();
  • rend() – it returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
auto iterator = it;

it = v1.rend();
  • cbegin() – it returns a constant iterator pointing to the first element in the vector.
auto iterator = it;

it = v1.cbegin();
  • cend() – it returns a constant iterator pointing to the theoretical element that follows the last element in the vector.
auto iterator = it;

it = v1.cend();
  • crbegin() – it returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
auto iterator = it;

it = v1.crbegin();
  • crend() – it returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
auto iterator = it;

it = v1.crend();
  • push_back() – it accepts a parameter and insert the element passed in the parameter in the vectors, the element is inserted at the end.
vector<int> vec1; //push elements

vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
  • insert() – it is used to insert an element at a specified position.
auto it= vec1.begin();
vec1.insert(it,5); //inserting 5 at the beginning of the vector
  • erase() – it is used to delete a specific element
vector<int> vec;
auto it= vec.begin();
vec.erase(it); // erasing the first element from the vector
  • pop_back() – it deletes the last element and returns it to the calling function.
vec.pop_back();
  • front() – it returns a reference to the first element of the vector.
vec.front();
  • back() – it returns a reference to the last element of the vector.
vec.back();
  • clear() – deletes all the elements from the vector.
vec.clear();
  • empty() – to check if the vector is empty or not.
vec.empty();
  • size() – returns the size of the vector
vec.size();

Example with Code :


// C++ program to illustrate the
// iterators in vector
#include <iostream>
#include <vector> //include vector

using namespace std;

int main()
{
    vector<int> vec;

    // push_back() function inserts element into the vector
    for (int it = 1; it <= 5; it++)
        vec.push_back(it);

    cout << "Output of begin and end: ";
    for (auto it = vec.begin(); it != vec.end(); ++it)
        cout << *it << " ";

    cout << "\nOutput of cbegin and cend: ";
    for (auto it = vec.cbegin(); it != vec.cend(); ++it)
        cout << *it << " ";

    cout << "\nOutput of rbegin and rend: ";
    for (auto it = vec.rbegin(); it != vec.rend(); ++it)
        cout << *it << " ";

    cout << "\nOutput of crbegin and crend : ";
    for (auto it = vec.crbegin(); it != vec.crend(); ++it)
        cout << *it << " ";

    cout << "\nThe front element of the vector: " << vec.front();
    cout << "\nThe last element of the vector: " << vec.back();
    cout << "\nThe size of the vector: " << vec.size();
    cout << "\nDeleting element from the end: " << vec[vec.size() - 1];
    vec.pop_back(); // pop the last element from the vector

    cout << "\nPrinting the vector after removing the last element:" << endl;
    for (int i = 0; i < vec.size(); i++)
        cout << vec[i] << " ";

    cout << "\nInserting 5 at the beginning:" << endl;
    vec.insert(vec.begin(), 5);
    cout << "The first element is: " << vec[0] << endl;
    cout << "Erasing the first element" << endl;
    vec.erase(vec.begin());
    cout << "Now the first element is: " << vec[0] << endl;

    if (vec.empty())
        cout << "\nvector is empty";
    else
        cout << "\nvector is not empty" << endl;

    vec.clear();  //clear all elements from the vector and return 0
    cout << "Size of the vector after clearing the vector: " << vec.size();

    return 0;
}

Output:

Other Functions:

  • max_size() – it returns the maximum number of elements that the vector can hold.
  • capacity() – it returns the size of the storage space currently allocated to the vector expressed as number of elements.
  • resize(n) – it returns the container so that it contains ‘n’ elements.
  • reverse() – it returns that the vector capacity be at least enough to contain n elements.
  • at(a) – it returns a reference to the element at position ‘a’ in the vector
  • data() – it returns a direct pointer to the memory array used internally by the vector to store its owned elements.
  • assign() – it returns new value to the vector elements by replacing old ones.
  • swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ.
  • emplace() – It extends the container by inserting new element at position
  • emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector
  • shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the

Example with Code :


// C++ program to illustrate the
// iterators in vector
#include <iostream>
#include <vector> //include vector

using namespace std;

int main()
{
    vector<int>vec;

    // push_back() function inserts element into the vector
    for (int it = 1; it <= 5; it++)
        vec.push_back(it);

    cout << "\nCapacity : " << vec.capacity();
    cout << "\nMax_Size : " << vec.max_size();

    // resizes the vector size to 4
    vec.resize(4);

    // prints the vector size after resize()
    cout << "\nSize : " << vec.size();
    vec.shrink_to_fit();
    cout << "\nVector elements are: ";
    for (auto it = vec.begin(); it != vec.end(); it++)
        cout << *it << " ";
    
    return 0;
}

Output:

Example with Code :

// C++ program to illustrate the
// capacity function in vector
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v;
    v.assign(5, 10);

    cout << "The vector elements are: ";
    for (int i = 0; i < v.size(); i++)
        cout << v[i] << " ";

    // pointer to the first element
    int *pos = v.data();

    cout << "\n The first element is " << *pos;

    // inserts at the beginning
    v.emplace(v.begin(), 5);
    cout << "\nThe first element is: " << v[0];

    // Inserts 20 at the end
    v.emplace_back(20);
    int n = v.size();
    cout << "\nThe last element is: " << v[n - 1];

    // two vector to perform swap
    vector<int> v1, v2;
    v1.push_back(1);
    v1.push_back(2);
    v2.push_back(3);
    v2.push_back(4);

    cout << "\n\nVector 1: ";
    for (int i = 0; i < v1.size(); i++)
        cout << v1[i] << " ";

    cout << "\nVector 2: ";
    for (int i = 0; i < v2.size(); i++)
        cout << v2[i] << " ";

    // Swaps v1 and v2
    v1.swap(v2);

    cout << "\nAfter Swap \nVector 1: ";
    for (int i = 0; i < v1.size(); i++)
        cout << v1[i] << " ";

    cout << "\nVector 2: ";
    for (int i = 0; i < v2.size(); i++)
        cout << v2[i] << " ";

    return 0;
}

Output:

To master C++ Standard Template Library (STL) in the most efficient and effective way, do check out this:

Video Tutorial:

This article is contributed by : Sayan Dutta to this article on csforall.in

Leave a Comment