Storing Units

Started by
10 comments, last by luca-deltodesco 15 years, 3 months ago
Quote:Original post by M4rtin
For Example:
Unit[1] <- The Unit I need.


Why do you need this one specifically?

How do you know that that's the one you need, and not Unit[2] for example?

(If you store them in a std::list instead, you should be able to use pointers, but that may not be the best idea.)

Quote:Original post by Ignifex
Although I do not know what solution you decided to take, I do not really see what you mean by "loosing" the pointer.


He meant that he loses it, presumably. Although I suppose it makes a kind of sense to describe a so-called "dangling" pointer as "loose" ;)

[Edited by - Zahlman on December 28, 2008 3:53:30 AM]
Advertisement
I'm not entirely sure how vectors are implemented, but as far as i'm aware when you erase an entry, all of the entries after the one erased are shifted down which means you would have to iterate over them to decrement their index.

An alternative would be to swap the one you want to erase with the last in the vector, swap the indices aswell, then erase only the last one. This ofcourse assumes that you do not need the order to be consistent.

template <class T>
void erase(std::vector<T> & vec, T ent)
{
int eind = ent.ind;
int last = vec.size()-1;

(vec[eind] = vec[last]).ind = eind;
vec[last] = ent;

vec.pop_back();
}

imagine if you will the following vector showing indices of entries, and you want to erase {3}

[0][1][2]{3}[4][5][6][7][8]<9> now do the swap
[0][1][2]<9>[4][5][6][7][8]{3} now fix the index of swapped
[0][1][2]<3>[4][5][6][7][8]{3} now pop last one off
[0][1][2]<3>[4][5][6][7][8]

This topic is closed to new replies.

Advertisement