.erase()
Published Aug 13, 2024
Contribute to Docs
The .erase()
function removes a single element or a range of elements from a specific position(s) in a vector. When it removes an element(s), the size of the vector decreases and the elements after the deleted one(s) are shifted to fill the gap. The position(s) of the element(s) to remove are identified using the .begin()
and/or .end()
functions.
Syntax
The following syntax is used to remove a single element from a vector:
vector.erase(position);
vector
: The vector to be iterated.position
: An iterator pointing to the position of the element to be removed.
Here is the syntax for eliminating a range of elements from the vector:
vector.erase(starting_position, ending_position);
starting_position
: An iterator indicating the beginning of the range to be removed.ending_position
: An iterator indicating the end of the range to be removed.
Examples
In the example below, the .erase()
function removes a single element from a vector:
#include <iostream>#include <vector>int main(){// Declare a vectorstd::vector<int> room;// Add valuesfor(int i=1; i<=10; i++) room.push_back(i);// Remove the 3rd elementroom.erase(room.begin()+2);// Print the remaining elements in the vectorstd::cout << "Rooms available:";for (unsigned i=0; i<room.size(); ++i)std::cout << ' ' << room[i];std::cout << '\n';return 0;}
The output of the above code is:
Rooms available: 1 2 4 5 6 7 8 9 10
The following example uses .erase()
to remove a range of elements from a vector:
#include <iostream>#include <vector>int main(){// Declare a vectorstd::vector<int> room;// Add valuesfor(int i=1; i<=10; i++) room.push_back(i);// Remove the last 3 elementsroom.erase(room.begin()+7, room.end());// Print the remaining elements in the vectorstd::cout << "Rooms available:";for (unsigned i=0; i<room.size(); ++i)std::cout << ' ' << room[i];std::cout << '\n';return 0;}
The output of the above code is as follows:
Rooms available: 1 2 3 4 5 6 7
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours