The Wayback Machine - https://web.archive.org/web/20240628053347/https://www.geeksforgeeks.org/vector-erase-and-clear-in-cpp/
Open In App

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

Last Updated : 09 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
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.



Previous Article
Next Article

Similar Reads

deque::clear() and deque::erase() in C++ STL
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::clear() The clear()
5 min read
Different ways to delete elements in std::map (erase() and clear())
This article deals with the deletion part of Maps. We can delete elements in std::map using two functions 1. Using erase() The erase() is used to erase the pair in the map mentioned in the argument, either its position, its value, or a range of numbers. We can use the erase function in the following ways: A. Remove using the Keyerase (key) Erases t
4 min read
Difference between std::remove and vector::erase for vectors
std::remove : It doesn't actually delete elements from the container but only shunts non-deleted elements forwards on top of deleted elements. vector::erase : Removes from the vector either a single element (position) or a range of elements ([first, last)). std::remove vs vector::erase By using erase all elements in a std::vector will be shifted by
4 min read
list erase() function in C++ STL
The list::erase() is a built-in function in C++ STL which is used to delete elements from a list container. This function can be used to remove a single element or a range of elements from the specified list container. Syntax: iterator list_name.erase(iterator position)or,iterator list_name.erase(iterator first, iterator last)Parameters: This funct
3 min read
multimap::erase() in C++ STL
multimap::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range. Syntax for erasing a key: multimap_name.erase(key) Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the multimap
4 min read
unordered_set erase() function in C++ STL
The unordered_set::erase() function is a built-in function in C++ STL which is used to remove either a single element or a group of elements ranging from start(inclusive) to end(exclusive). This decreases the size of a container by the number of elements removed.Note: Buckets in unordered_set are numbered from 0 to n-1, where n is the total number
3 min read
unordered_map erase in C++ STL
erase function is used to erase elements from the unordered_map. There are three type of erase functions supported by unordered_map : erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator. Syntax unordered_map.erase(const iterator); erasing by key: It takes a key as a parameter and erases the
2 min read
unordered_multiset erase() function in C++ STL
The unordered_multiset::erase() function is a built-in function in C++ STL which is used to remove either a single element or, all elements with a definite value or, a range of elements ranging from start(inclusive) to end(exclusive). This decreases the size of the container by the number of elements removed. Syntax: unordered_multiset_name.erase(i
2 min read
unordered_multimap erase in C++ STL
unordered_multimap::erase() is a built in function in C++ STL which removes the element from given range, by position and by key. There are three variant of this function in C++ STL. There are following type of erase() functions in C++ for unordered_multimap. By position : It removes element from unordered_multimap by given position and return an i
4 min read
Erase-Remove Idiom in C++
Erase-Remove-Idiom is a C++ STL (Standard Template Library) technique to remove elements from a container. It is used to remove all the elements satisfying certain conditions from the container. The erase-remove idiom is especially useful in array-based containers like vectors, where each elimination requires all the remaining elements to adjust. I
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg