I have a map that stores pointers to an object by their ID.
typedef std::map<unsigned int, Entity*> entityMap;
entityMap entitymap;
To assign an ID to Entity I could just take the newest value in entitymap and increase it by 1.
Entity *entity = new Entity;
entity->id = /*newest entity+1*/;
entitymap.insert(std::pair<unsigned int,Entity*>(entity->id,entity));
But the number could become unnecessarily big because every now and then an Entity is deleted and removed from the map.
std::map<unsigned int,Entity*>::iterator it;
it = entitymap.find(EntityID);
if(it != entitymap.end())
{
Entity *entity= it->second;
entitymap.erase(it);
}
delete entity;
So I could have a map that holds these values;
1,2,4,8,10
In which case I'd like the next Entity to claim the ID 3
.
Using map. keySet() method if you want to retrieve Keys only. If you only want to retrieve keys only, Map. keySet() method returns a Set of keys contained in the map.
The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap . In the example below, we will first create a HashMap object, insert some values in it, and then use keySet() to get the keys.
Since the IDs are ordered numerically, you could walk through the entire map until you find a "hole":
unsigned int i = 1; // or whatever your smallest admissable key value is
for (auto it = m.cbegin(), end = m.cend();
it != end && i == it->first; ++it, ++i)
{ }
// now i is the next free index
This may take long if the map is large and the first hole is near the end. You could check first if the largest key value (given by m.crbegin()->first
) is significantly larger than m.size()
before embarking on this exploration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With