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

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

Last Updated : 09 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
How to Erase Duplicates and Sort a Vector in C++?
In C++, vector is a sequential template class, part of STL(Standard Template Library). A vector in C++ is a resizable array because it can change its size either by growing or shrinking when an element is added or removed from the vector, respectively. Hence, it is also called a dynamic array because of its property of growing and shrinking in size
3 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_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
Erase Range of Elements From List Using Iterators in C++ STL
Prerequisites:List in C++Iterators in C++ A list is a type of container which requires the same properties as a doubly linked list. We can insert elements from either side of the list, but accessing elements with an index is not possible in the list. So, removing elements from the list is not an easy task. But, we have a method to remove multiple e
2 min read
set::erase in C++ STL
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::erase()erase() function is used to remove elements from a containe
5 min read
map erase() function in C++ STL
map::erase() is a built-in function in C++ STL that is used to erase elements from the container. It can be used to erase keys and elements at any specified position or a given range. The syntax for erasing a key:map_name.erase(key)Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the map container
4 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(it
2 min read
std::string::erase in C++
The std::string::erase() function erases the whole or a part of the string shortening its length. It is a member function of std::string class so we can directly use it with string objects. The characters affected depend on the function version used. There are 5 overloaded versions of the string::erase() function that can be used for following diff
5 min read
vector::front() and vector::back() in C++ STL
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::front() This function can be used to fetch the first element of a vector container.Syntax : vectorname.front() Parameters : No value is needed to pass as
3 min read
vector::empty() and vector::size() in C++ STL
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::empty() The empty() function is used to check if the vector container is empty or not.Syntax : vectorname.empty() Parameters : No parameters are p
5 min read
vector::at() and vector::swap() in C++ STL
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::at() at() function is used reference the element present at the position given as the parameter to the function. Syntax: vectorname.at(position) Parameter
4 min read
vector :: cbegin() and vector :: cend() in C++ STL
Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. vector::cbegin() The function returns an iterator which is used to iterate container. The iterator points to the beginning of the vector.Iterator cannot modify the contents of the vector. Synta
2 min read
vector::operator= and vector::operator[ ] in C++ STL
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::operator=This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
vector::begin() and vector::end() in C++ STL
Vectors are the 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::begin()begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional
3 min read
vector::push_back() and vector::pop_back() in C++ STL
STL vector container provides two functions: push_back() and pop_back() for insertion and deletion from the end of the vector. In this article, we will learn discuss about these methods. vector::push_back()The push_back() function is used to push or insert an element into a vector at the back. It means that the new value is inserted into the vector
3 min read
vector::crend() &amp; vector::crbegin() with example
These functions return useful iterators to access vector elements in reverse order (from end to beginning) Using vector::crend() It's a public member function that returns a const_reverse_iterator pointing to the element preceding the first element. Return Value A const_reverse_iterator to the reverse end of the sequence. Syntax: const_reverse_iter
2 min read
How to flatten a Vector of Vectors or 2D Vector in C++
Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector. Examples: Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]] Output: 1 2 3 4 5 6 7 8 Input: vector = [[1, 2], [3], [4, 5, 6, 8]] Output: 1 2 3 4 5 6 8 Algorithm: 2D Vector can be flattened using iterators.Store starting and ending iterator of every vector in two arrays, iStar
2 min read
Initializing Vector using an Existing Vector in C++ STL
A vector is a type of container which can store objects of similar data type. Vector acts like a dynamic array where we can insert elements and the size of the array increases depending upon the elements inserted. Syntax: vector&lt;data_structure/type&gt; vector_name(size, item) To know more about vectors refer to vectors in C++. The 3D vector in C
5 min read
std::vector::resize() vs. std::vector::reserve()
In C++, vectors are dynamically resizable arrays provided by STL. They can automatically change their size according to the number of elements and users also can change its size using the std::vector::resize()and std::vector::reserve(). But there is some difference in how these functions works. In this article, we will learn what are the difference
5 min read
Is std::vector or boost::vector Thread Safe?
In C++, a common question that arises is: Is std::vector or boost::vector thread-safe? The straightforward answer is no, neither std::vector nor boost::vector is thread-safe. In this article, we will learn why std::vector and boost::vector are not thread-safe and explore some practical alternatives for making them safe to use in a multi-threaded en
5 min read
forward_list::clear() and forward_list::erase_after() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps tr
4 min read
map::clear() in C++ STL
Map is dictionary like data structure. It is an associative array of (key, value) pair, where only single value is associated with each unique key. map::clear() clear() function is used to remove all the elements from the map container and thus leaving it's size 0. Syntax: map1.clear() where map1 is the name of the map. Parameters: No parameters ar
2 min read
list::clear() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::clear()clear() function is used to remove all the elements of the list container, thus making
1 min read
Article Tags :
Practice Tags :