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
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);
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"
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.