How to Work with Vectors in C++ STL

The vectors in the C++ Standard Template Library are dynamic arrays that can increase or decrease in size. For efficient data manipulation, vectors offer powerful built-in functions and flexibility. Today, we will look at insertion, deletion, iteration, capacity management, sorting, and swapping operations, with an example.

What is Vector and its Properties

A Vector is a dynamic array that allows elements to be added or removed dynamically without worrying about memory allocation. It is part of <vector>header file and provides functionalities like dynamic resizing, access to elements using indices, sorting, reversing and swapping, etc. Let the vector elements having indices range form ‘0’ to ‘n-1’ , (where the ‘n’ is the number of elements in the vector).
Vectors allow fast random access, efficient insertion/deletion at the end. However, they are not thread-safe by default, so concurrent modifications require external synchronization. Vector are widely used when the number of elements is unknown at compile time. Unlike arrays, which have a fixed size, but vector not!

Including required libraries

these are all libraries required for working with vectors effectively and easily.

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

 

  • <iostream>allows for the input and output operations
  • <vector> Provide access to vector-related functions
  • <algorithm> includes useful algorithms like sorting and reversing, etc.

Creating and Initializing Vectors

There are multiple ways to initialize vector depending on requirements. We can directly initialize the vector with some predefined values(ex. v1name={7,3,6}), also fixed size with default value (ex. v2name=(size, deafult value) or create new vector by copying another vector (v3(v1))
Example-

vector<int> v1={40,30,20,10,65,70,55,78};
vector<int> v2(10,100);
vector<int> v3(v1);

Inserting Elements into Vector

Vectors allow dynamic insertion of elements using different methods. The push_back() function appends an element at the end ,while the same operation is performed by emplace_back() but it is more efficient. The inserting element at the specified position and multiple elements can be inserted at once by using the insert() function.

Example-

v1.push_back(10);
v1.emplace_back(15);
v1.insert(v1.begin()+3,90);
v1.insert(v1.end(),{50,60,70});

cout<<"\nVector v1 after v1.pushback(10) and v1.emplace_back(15) respectively and insert() :"<<endl;
for(size_t i = 0; i < v1.size(); i++){
    cout << v1[i] << " ";
}

 

Accessing Vector Elements

Indices can be used to access the elements of Vector, front(), back(), and at() methods are mainly used. The front() function is used to retrieve the first element, while the back() for the last element of that vector. at() is used to access the element according to the index provided.

Example-

cout<<"\nFirst Element: " << v1.front() <<endl;
cout<<"Last Element: " << v1.back() <<endl;
cout<<"Element at index 3: " << v1.at(3) <<endl;

Iterating Over a Vector

There are multiple ways to iterate over a vector.

Index based loop
cout<< "\nVector Elements using different methods:" <<endl;
cout<< "1.Using index: "<<endl;
for (size_t i = 0; i < v1.size(); i++){
    cout << v1[i] <<endl;
}

Range based loop
cout << "2.Use range-based loop: "<<endl;
for (int x : v1){
    cout << x <<endl;
}
Iterator based loop
cout << "3.Use iterator: "<<endl;
for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it){
    cout << *it <<endl;
}

Removing Elements from a Vector

To remove elements from the vector pop_back() and erase() functions will be used. For reducing the element from the last and reducing the vector size by 1 the pop_back() function is used. The erase() function is used for deleting an element at a specific position or a range of elements.

Example-

v1.pop_back();
v1.erase(v1.begin()+2);
cout<<"\nVector v1 after pop_back() and removing element at index 2 :"<<endl;
for (size_t i = 0; i < v1.size(); i++){
    cout<< v1[i] << " ";
}

Vector Resizing and Capacity Management

Vectors can adjust their size dynamically. resize(), capacity(), and shrink_to_fit() these are some functions which help to control their behavior. The resize() function changes the vector’s size, and if new elements are added, they are initialized to a specified value. The capacity() function returns the current capacity of the vector it may be larger than the actual size due to preallocation of memory. The shrink_to_fit() function reduces the capacity to match the size orĀ  freeing up unused memory.

Example-

v1.resize(10, 0);
cout << "\nSize of v1 after resizing : " << v1.size() <<endl;
cout<< "Capacity of v1 : " << v1.capacity() << endl;
v1.shrink_to_fit();
cout << "Size after shrink_to_fit: " << v1.size() <<endl;
cout<< "Capacity of v1 : " << v1.capacity() << endl;

Sorting and Reversing a Vector

Sorting is fundamental operation in programming, sort() function allows sorting vectors in ascending or descending order, while the reverse() function reverses the order of elements

Example-

sort(v1.begin(), v1.end());
sort(v1.begin(), v1.end(), greater<int>());
reverse(v1.begin(), v1.end());
for (size_t i = 0; i < v1.size(); i++){
    cout << v1[i] << " ";
}

Swapping Two Vectors

For the swapping of the contents of two vectors efficiently, the swap() function is used. Swapping is useful when handling large datasets there is no need to manually copying elements.

Example-

sort(v1.begin(), v1.end());
sort(v1.begin(), v1.end(), greater<int>());
reverse(v1.begin(), v1.end());

Complete Code and Output

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    
    vector<int> v1 = {40,30,20,10,65,45,55,78};
    vector<int> v2(10, 100);
    vector<int> v3(v1); // Copy v1 in v3

    //INSERTION AND ADD ELEMENTS INTO VECTOR
    v1.push_back(12);
    v1.emplace_back(15);
    v1.insert(v1.begin() + 3, 90);
    v1.insert(v1.end(), {50, 60, 70});
    cout<<"\nVector v1 after v1.pushback(10) and v1.emplace_back(15) respectively and insert() :"<<endl;
    for (size_t i = 0; i < v1.size(); i++){
        cout << v1[i] << " ";
    }

    //ACCESSING ELMENTS FROM VECTOR
    cout << "\nFirst Element: " << v1.front() << endl;
    cout << "Last Element: " << v1.back() << endl;
    cout << "Element at index 3: " << v1.at(3) << endl;

    //ITERATING AND DISPLAY THE ELEMENTS OF VECTOR
    cout << "\nVector Elements using different methods:" << endl;

    cout << "1.Using index: "<<endl;
    for (size_t i = 0; i < v1.size(); i++){
        cout << v1[i] <<endl;
    }

    cout << "2.Use range-based loop: "<<endl;
    for (int x : v1){
        cout << x <<endl;
    }

    cout << "3.Use iterator: "<<endl;
    for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it){
        cout << *it <<endl;
    }

    //REMOVE ELEMENTS FROM VECTOR
    v1.pop_back();
    v1.erase(v1.begin() + 2);
    cout<<"\nVector v1 after pop_back() and removing element at index 2 :"<<endl;
    for (size_t i = 0; i < v1.size(); i++){
        cout<< v1[i] << " ";
    }

    //RESIZE AND CAPACITY OF VECTOR
    v1.resize(10, 0);
    cout << "\nSize of v1 after resizing : " << v1.size() <<endl;
    cout<< " Capacity of v1 : " << v1.capacity() << endl;
    v1.shrink_to_fit();
    cout << "Size after shrink_to_fit: " << v1.size() <<endl;
    cout<< " Capacity of v1 : " << v1.capacity() << endl;

    //SORTING AND REVERSING
    sort(v1.begin(), v1.end());
    sort(v1.begin(), v1.end(), greater<int>());
    reverse(v1.begin(), v1.end());
    //SWAPPING
    cout << "\n-|-Before Swapping -|- ";
    cout << "\nElements of v1 : ";
    for (int x : v1){
        cout << x << " ";
    }
    cout << "\nElements of v2 : ";
    for (int x : v2){
        cout << x << " ";
    }
    v1.swap(v2);
    cout << "\n-|-After Swapping -|- ";
    cout<<"\nElements of v1 :";
    for (int x : v1){
        cout<< x <<" ";
    }

    cout<<"\nElements of v2 :";
    for (int x : v2){
        cout<< x << " ";
    }
    return 0;
}

 

Output

Vector v1 after v1.pushback(10) and v1.emplace_back(15) respectively and insert() :
40 30 20 90 10 65 45 55 78 12 15 50 60 70 
First Element: 40
Last Element: 70
Element at index 3: 90

Vector Elements using different methods:
1. Using index: 
40
30
20
90
10
65
45
55
78
12
15
50
60
70
2.Use range-based loop: 
40
30
20
90
10
65
45
55
78
12
15
50
60
70
3.Use iterator: 
40
30
20
90
10
65
45
55
78
12
15
50
60
70

Vector v1 after pop_back() and removing element at index 2 :
40 30 90 10 65 45 55 78 12 15 50 60 
Size of v1 after resizing : 10
 Capacity of v1 : 16
Size after shrink_to_fit: 10
 Capacity of v1 : 10

-|-Before Swapping -|- 
Elements of v1 : 10 12 15 30 40 45 55 65 78 90 
Elements of v2 : 100 100 100 100 100 100 100 100 100 100 
-|-After Swapping -|- 
Elements of v1 :100 100 100 100 100 100 100 100 100 100 
Elements of v2 :10 12 15 30 40 45 55 65 78 90

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top