我有一个映射,它通过对象的 ID 存储指向对象的指针。
typedef std::map<unsigned int, Entity*> entityMap;
entityMap entitymap;
要为实体分配一个 ID,我可以将 entitymap 中的最新值增加 1。
Entity *entity = new Entity;
entity->id = /*newest entity+1*/;
entitymap.insert(std::pair<unsigned int,Entity*>(entity->id,entity));
但是这个数字可能会变得不必要地大,因为不时会有一个实体被删除并从 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;
所以我可以有一个包含这些值的 map ;
1,2,4,8,10
在这种情况下,我希望下一个实体声明 ID 3
。
最佳答案
由于 ID 是按数字顺序排列的,因此您可以遍历整个 map ,直到找到一个“洞”:
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
如果 map 很大并且第一个洞靠近尽头,这可能会花费很长时间。在开始探索之前,您可以先检查最大键值(由 m.crbegin()->first
给出)是否明显大于 m.size()
。
关于c++ - 获取 map 中的第一个可用键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8696545/