Deleting Class Iterator

closed account (2NywAqkS)
How is it possible to delete an iterator of a class vector from within the class.

for example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class apple
{
  public:
    void Squash_Apple();
};

void apple::Squash_Apple();
{
  //What goes in here
}

std::vector<apple> apple_vector;

int main()
{
  for(int i = 0; i < 10; i++)
  {
     apple_vector.push_back(apple);
  }
apple_vector[7].Squash_Apple();
}


Please feel free to ask questions. Any help is much appreciated.

Thanks, Rowan
Last edited on
I don't understand. apple_vector is empty. What iterator is it you want to "delete"?
closed account (2NywAqkS)
Oh yeah, sorry. I will just change that. but despite this how would I do it?
I feel that the apple should not have to care if it's being stored in a vector or not.
Can't you just do apple_vector.erase(apple_vector.begin() + 7); instead of apple_vector[7].Squash_Apple();


closed account (2NywAqkS)
This is just an example. If it helps ignore the example. I was just wandering if there was an easy piece of code to go in in the squash apple function.
If want such a function you have to at least have access to the vector from inside Squash_Apple(). You could pass the vector by reference to the function or if the vector is always the same, and it's global as in the example you have access to it that way.

Inside the function you could search for the object in the vector that has the same memory address as this. and then delete it.
1
2
3
4
5
6
7
8
for (std::vector<apple>::iterator it = apple_vector.begin(); it != apple_vector.end(); ++it)
{
	if (&*it == this)
	{
		apple_vector.erase(it);
		break;
	}
}


I don't really like this function :P
Last edited on
closed account (2NywAqkS)
Thanks, just what i was after :)
Topic archived. No new replies allowed.