How do I remove an element from a vector? For example, removing the 3 from a vector containing 1,2,3,4 so it becomes 1,2,4
This is a discussion on Removing element from vector? within the C++ Programming forums, part of the General Programming Boards category; How do I remove an element from a vector? For example, removing the 3 from a vector containing 1,2,3,4 so ...
How do I remove an element from a vector? For example, removing the 3 from a vector containing 1,2,3,4 so it becomes 1,2,4
Call std::vector.erase with the index you want to erase, in case the 3rd index:
Or if you have an iterator, that should work too.Code:std::vector myvec; // Assume vector is filled with data myvec.erase(myvec.begin() + 2);
Last edited by Elysia; 02-03-2008 at 11:24 PM.
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^
or if you want to remove all elements equal to 3 so that 1,3,2,3,4,3 becomes 1,2,4 use the erase-remove idiom:
Code:v.erase( remove( v.begin(), v.end(), 3 ), v.end() );
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Right, silly me. 0-based index.
/slaps self.
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^
note that vector's erase takes linear time (proportional to the size of the dataset). If you are doing this relatively often, you should be using something like linked lists.