Open In App

vector erase() and clear() in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Prerequisite: Vector in C++

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

vector::clear()

The clear() function is used to remove all the elements of the vector container, thus making it size 0.

Syntax:

vector_name.clear()

Parameters: No parameters are passed.

Result: All the elements of the vector are removed (or destroyed).

Example:

Input:    myvector= {1, 2, 3, 4, 5};
        myvector.clear();

Output:    myvector= {}

C++




// C++ program to demonstrate
// Implementation of clear() function
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    vector<int> myvector;
    myvector.push_back(1);
    myvector.push_back(2);
    myvector.push_back(3);
    myvector.push_back(4);
    myvector.push_back(5);
 
    // Vector becomes 1, 2, 3, 4, 5
 
    myvector.clear();
    // vector becomes empty
 
    // Printing the vector
    for (auto it = myvector.begin(); it != myvector.end();
         ++it)
        cout << ' ' << *it;
    return 0;
}


Output

No Output

Time Complexity: O(N)
Auxiliary Space: O(1)
All elements are destroyed one by one.

Errors and Exceptions

  1. It has a no exception throw guarantee.
  2. It shows an error when a parameter is passed.

vector::erase()

erase() function is used to remove elements from a container from the specified position or range.

Syntax: 

vector_name.erase(position);    for deletion at specific position
vector_name.erase(starting_position, ending_position);    // for deletion in range

Parameters:

  • Position of the element to be removed in the form of an iterator.
  • The range is specified using start and end iterators.

Result: Elements are removed from the specified position of the container.

Example:

Input:    myvector= {1, 2, 3, 4, 5}, iterator= myvector.begin()+2
        myvector.erase(iterator);
Output:    1, 2, 4, 5

Input:    myvector= {1, 2, 3, 4, 5, 6, 7, 8}, iterator1= myvector.begin()+3, iterator2= myvector.begin()+6
        myvector.erase(iterator1, iterator2);
Output:    1, 2, 3, 7, 8

Removing an element from a particular position

Example:

C++




// C++ program to demonstrate
// working of erase() function
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    vector<int> myvector{ 1, 2, 3, 4, 5 };
    vector<int>::iterator it;
 
    it = myvector.begin();
    myvector.erase(it);
 
    // Printing the Vector
    for (auto it = myvector.begin(); it != myvector.end();
         ++it)
        cout << ' ' << *it;
    return 0;
}


Output

 2 3 4 5

Time Complexity: O(N)
Auxiliary Space: O(1)

Removing a particular element

To delete a particular element based on its value, first, we need to know about its position and we can find it using the find() function

Example:

C++




// C++ program to remove element based on its value
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector<int> vector = { 1, 2, 3, 3, 4, 5 };
    cout << "vector before deleting " << endl;
    for (auto element : vector) {
        cout << element << " ";
    }
 
    // finding the position of the element in the vector
    int valueToBeDeleted = 3;
    auto it = find(vector.begin(), vector.end(),
                   valueToBeDeleted);
 
    if (it != vector.end()) {
        vector.erase(it);
    }
 
    cout << endl
         << "Vector after deleting  valueToBeDeleted "
         << endl;
    for (auto element : vector) {
        cout << element << " ";
    }
    cout << endl;
 
    return 0;
}


Output

vector before deleting 
1 2 3 3 4 5 
Vector after deleting  valueToBeDeleted 
1 2 3 4 5 

Removing elements within a range

C++




// C++ program to demonstrate
// Implementation of erase() function
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    vector<int> myvector{ 1, 2, 3, 4, 5 };
    vector<int>::iterator it1, it2;
 
    it1 = myvector.begin();
    it2 = myvector.end();
    it2--;
    it2--;
 
    myvector.erase(it1, it2);
 
    // Printing the Vector
    for (auto it = myvector.begin(); it != myvector.end();
         ++it)
        cout << ' ' << *it;
    return 0;
}


Output

 4 5

Time Complexity: O(N)
Auxiliary Space: O(1)

Removing vector pair elements

Example:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to print vector pair elements
void print(vector<pair<int, string> >& vec)
{
    cout << "[";
    for (int i = 0; i < vec.size(); i++) {
        cout << "{" << vec[i].first << "," << vec[i].second
             << "}";
        if (i < vec.size() - 1)
            cout << ", ";
    }
    cout << "]" << endl;
}
 
int main()
{
 
    vector<pair<int, string> > x = { { 1, "apple" },
                                     { 2, "banana" },
                                     { 3, "cherry" },
                                     { 4, "Guava" } };
 
    // Remove the element at position 1 (index 0)
    x.erase(x.begin());
    print(x); // Print [{2,banana}, {3,cherry}, {4,Guava}]
 
    // Remove the elements at positions 0 and 1 (indexes 0
    // and 1)
    x.erase(x.begin(), x.begin() + 2);
    print(x); // Print [{4,Guava}]
 
    // Clear the vector
    x.clear();
    print(x); // Print nothing (only empty brackets)
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

[{2,banana}, {3,cherry}, {4,Guava}]
[{4,Guava}]
[]

Time Complexity: O(N)
Auxiliary Space: O(1)

Errors and Exceptions

  1. It has no exception throw guarantee if the position is valid. 
  2. Shows undefined behavior otherwise.

Application

Given a list of integers, remove all the even elements from the vector and print the vector.

Input:

1, 2, 3, 4, 5, 6, 7, 8, 9

Output:

1 3 5 7 9

Explanation: 2, 4, 6, and 8 which are even and erased from the vector

Algorithm

  1. Run a loop to the size of the vector. 
  2. Check if the element at each position is divisible by 2, if yes, remove the element and decrement the iterator. 
  3. Print the final vector.

The below program implements the above approach.

 

C++




// C++ program to demonstrate
// Application of erase() function
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    vector<int> myvector{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
    for (auto i = myvector.begin(); i != myvector.end();
         ++i) {
        if (*i % 2 == 0) {
            myvector.erase(i);
            i--;
        }
    }
 
    // Printing the vector
    for (auto it = myvector.begin(); it != myvector.end();
         ++it)
        cout << ' ' << *it;
    return 0;
}


Output

 1 3 5 7 9

Time Complexity: O(N) in the worst case as an erase takes linear time.

clear() vs erase(), when to use what?

clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using the clear() function. 

erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.



Last Updated : 09 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads