c++ - 获取 map 中的第一个可用键

标签 c++ map

我有一个映射,它通过对象的 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/

相关文章:

c++ - C 字符串映射键

带孔的 html 区域标记

map - 悬停在特定国家/地区时,在空白世界地图上突出显示国旗

c++ - 是否允许在默认成员初始值设定项中调用非静态成员函数?

c++ - g++、 double 、优化和一个大 WTF

objective-c - iOS App的预测街道地址?

json - 如何用 JSON 表示 map 列表

c++ - 如何在cpp和c中不使用cout/printf输出文本?

c++ - 使用 OpenSSL 的相互认证总是成功的

c++ - 静态 __forceinline 或 __forceinline 静态