I am trying to delete an element in a vector of Objects. The vector is filled with instances of Object and at some point, I want to remove a certain element in a vector not by index, but by the element itself.
A simple example would be:
std::vector< string > strVector;
strVector.push_back( "abc" );
strVector.push_back( "def" );
strVector.push_back( "ghi" ); // So strVector should contain "abc", "def", and "ghi"
How do I remove “ghi” from that vector? Note that I don’t know where “ghi” is in that vector.
// Something like this. Assume strVector = [ "abc", "cba", "ccb", "bac", "aaa" ]
strVector.removeElement( "ccb" );
A more relevant example to what I a working on:
class MyClass {
std::vector< Object > myObjVector;
void main( ARGS ) {
for ( int i = 0; i < 10; i++ ) {
Object myObject = Object( );
myObjVector.push_back( myObject );
}
int j = getANumber( ); // j could be any number within the size of the vector
Object myOtherObject = myObjectVector.at( j );
// How do I erase myOtherObject (which is an object inside the vector) ?
removeFromVector( myOtherObject );
}
}
I hope the question’s clear. Thanks in advance.
EDIT: I figured it out, thanks to all those who answered. The trick was to give the class something unique that identifies it (like a name or a tag, as long as they are guaranteed to be unique) then use the erase-remove idiom to remove the object from the array.
If your use-case has no duplicates, then you are better off using an
std::setand using the std::set::erase which takes a value.If you need to cope with duplicates, then you have to specify the desired behaviour of the removal. Should it remove one or all of the elements matching a value? Do you care about preserving the order of the remaining elements? If you require using a vector, then lokk at the erase-remove idiom. But note that
std::vector::erasehas linear time complexity, whereas the relevant variant ofstd::set::erasehas logarithmic time complexity. And erase-remove would remove all elements equal to the given value.Note: if you want to use an
std::setfor a user defined type, you must provide either a less-thanbool operator<(const UserType&) constor a comparison function or functor, implementing strict weak ordering.