Skip to content
Related Articles

Related Articles

vector erase() and clear() in C++
  • Difficulty Level : Easy
  • Last Updated : 28 Oct, 2020

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

vector::clear()

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

vectorname.clear()
Parameters :
No parameters are passed.
Result :
All the elements of the vector are
removed ( or destroyed )

Examples: 

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

Input  : myvector= {};
         myvector.clear();
Output : myvector= {}

Errors and Exceptions
1. It has a no exception throw guarantee. 
2. Shows error when a parameter is passed.

CPP




// CPP program to illustrate
// 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) 
All elements are destroyed one by one.

vector::erase()

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

1. vectorname.erase(position)
2. vectorname.erase(startingposition, endingposition)
Parameters :
Position of the element to be removed in the form of iterator.
or the range specified using start and end iterator.
Result :
Elements are removed from the specified
position of the container.

Examples: 

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

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

Errors and Exceptions
1. It has a no exception throw guarantee if the position is valid. 
2. Shows undefined behavior otherwise.
Removing an element from a particular position:

CPP




// CPP program to illustrate
// 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


Removing elements within a range:

CPP




// CPP program to illustrate
// 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

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 are erased from the vector

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

CPP




// CPP program to illustrate
// 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(N2) 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 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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :