Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first available key in map

Tags:

c++

map

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.

like image 822
natli Avatar asked Jan 02 '12 00:01

natli


People also ask

How do I get just the map key?

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.

How do I get a hash map key?

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.


1 Answers

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.

like image 78
Kerrek SB Avatar answered Sep 23 '22 08:09

Kerrek SB