Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove ith item from a C++ std::vector [duplicate]

Tags:

c++

vector

How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

pList.remove(i); 
like image 828
kralco626 Avatar asked Dec 14 '10 18:12

kralco626


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 I remove something from vector?

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

How do you remove an element from a vector in a loop?

To delete single element from a vector using erase() function, pass the iterator of element to it like erase(it). It will delete the element pointed by the iterator the it variable. To delete multiple elements from a vector using erase() function, pass the iterator range to it like erase(start, end-1).


2 Answers

pList.erase(pList.begin()+i); 

To remove element with index i.

like image 38
Vladimir Avatar answered Sep 30 '22 00:09

Vladimir


Here is an O(1) solution, assuming you don't care about the order of elements:

#include <algorithm>  // ...  {     using std::swap;     swap(pList[i], pList.back());     pList.pop_back(); } 

For PODs, assignment is faster than swapping, so you should simply write:

pList[i] = pList.back(); pList.pop_back(); 

In C++11, you can forget the above distinction and always use move semantics for maximum efficiency:

if (i != pList.size() - 1) {     // Beware of move assignment to self     // see http://stackoverflow.com/questions/13127455/     pList[i] = std::move(pList.back()); } pList.pop_back(); 
like image 105
fredoverflow Avatar answered Sep 29 '22 23:09

fredoverflow