Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I erase an element from std::vector<> by index?

I have a std::vector<int>, and I want to delete the n'th element. How do I do that?

std::vector<int> vec;  vec.push_back(6); vec.push_back(-17); vec.push_back(12);  vec.erase(???); 
like image 735
dau_man Avatar asked May 17 '09 17:05

dau_man


People also ask

How do I remove a specific element from a vector in C++?

The erase() function can remove an element from the beginning, within, or end of the vector. In order to remove all the elements from the vector, using erase(), the erase() function has to be repeated the number of times there are elements, beginning from the first element.

How do you remove an element from the end of a vector?

pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1. 1.


1 Answers

To delete a single element, you could do:

std::vector<int> vec;  vec.push_back(6); vec.push_back(-17); vec.push_back(12);  // Deletes the second element (vec[1]) vec.erase(std::next(vec.begin())); 

Or, to delete more than one element at once:

// Deletes the second through third elements (vec[1], vec[2]) vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3)); 
like image 142
mmmmmmmm Avatar answered Oct 06 '22 23:10

mmmmmmmm