How can I remove an element at a specified index in a vector, and then return that element? Is there a method for that?
Asked
Active
Viewed 1,499 times
0
-
Does it have to be in that order? You can use `operator[]` or `at()`, followed by `erase()` if not. – chris Nov 21 '12 at 19:08
-
Duplicate? http://stackoverflow.com/questions/39912/how-do-i-remove-an-item-from-a-stl-vector-with-a-certain-value – Roman Byshko Nov 21 '12 at 19:08
-
@Beginner, Not really. It isn't searching by value, so using `remove` is a bit pointless. – chris Nov 21 '12 at 19:09
3 Answers
5
erase
can remove an element at a specified index, but does not return that element.
You can just do:
aboutToBeErased = myVector.at(index);
myVector.erase(myVector.begin() + index);
Be careful though, vectors are not good at removing elements that aren't at the end of the vector. This can be a costly operation for large vectors.

llakais
- 1,577
- 1
- 12
- 18
-
2
-
for the erase line, I got error "IntelliSense: too few arguments in function call" – Chin Nov 21 '12 at 19:13
-
3
To get the element, you can use
std::vector::at()
value = mVector.at(n);
To erase,
std::vector::erase()
The following would erase item no.n+1
and resize your vector.mVector.erase (mVector.begin()+n);
Erase shifts all elements and hence, indexes if you do erase an element in the middle.

Anirudh Ramanathan
- 46,179
- 22
- 132
- 191
2
Here is a function, written in C++11, that will get the nth element from a vector and erase it reasonably efficiently:
template<typename Vector>
typename Vector::value_type getAndErase( Vector& vec, size_t index )
{
Assert( index < vec.size() );
typename Vector::value_type retval = std::move(vec[index]);
vec.erase( vec.begin()+index );
return retval;
}

Yakk - Adam Nevraumont
- 262,606
- 27
- 330
- 524