SteveL
SteveL

Reputation: 3389

C++ : vector.erase(this)

I have an std::vector that holds all the objects and is passed to them in every frame, so that every object can access other objects. My question is how can an object can delete itself from the vector?

This doesn't work:

vector.erase(this);

Is there any other solution for this?

Upvotes: 1

Views: 603

Answers (5)

bobah
bobah

Reputation: 18864

You can do it as:

vec.erase(vec.begin() + (this - &vec.front()));

if you are sure that the element is from the vector indeed

Upvotes: 1

Niklas Andréasson
Niklas Andréasson

Reputation: 198

As mentioned you can use std::find ( http://www.cplusplus.com/reference/algorithm/find/ ) This requires you to overload the == operator if I'm not mistaken.

For example

std::vector<YourObjectType>::iterator it = find(yourVector.begin(), yourVector.end(), referenceToObject);

bool operator == (const YourObjectType* object) {return object == this; }

And then you just use yourVector.erase(it);

Upvotes: 1

PermanentGuest
PermanentGuest

Reputation: 5331

Alternatively you could use a set and use set.erase(this)

Upvotes: 1

Jack
Jack

Reputation: 133577

You need to delete the element by accessing its iterator, this can be done through std::find, or if you know the index (less complexity) through:

vector.begin() + indexOfElement

so that you can delete it:

vector<Type>::iterator it = yourVector.begin() + index;
yourVector.erase(it);

Mind that, since a vector stores its data in an array format, this causes all elements after the one you are deleting to be shifted to the left (which is expensive). Consider using a std::list instead if you don't need random access.

Upvotes: 4

dirkgently
dirkgently

Reputation: 111130

erase requires an iterator. this is a pointer available within member functions/class definition. Also, erase needs to be called on an instance of vector -- you cannot use vector.erase.

The object can't delete itself. You will need to pass an iterator. You can use std::find to find if the object exists within the vector and then pass that along.

Upvotes: 8

Related Questions