持有 unordered_map 个元素到 pointer/iterator

Holding unordered_map element to a pointer/iterator

每次我使用 find 查找一个元素,因此,我有一个返回给它的指针(用迭代器描述它比用指针更好)。但是,如果元素不存在,我就去创建它。

问题是,在这两种情况之后,我都希望有一些东西可以指向该元素,无论它是否存在(因为我确保我创建了它)。我的解决方案是使用 find(第二次,我猜这是昂贵的),但我认为可以有一种统一的方式来保存对项目的引用而无需进行第二次搜索(通过之前的 find 或在创建项).

这可能吗?

使用std::unordered_map::insert.

它的return值为std::pair<iterator,bool>,其中布尔值表示实际插入是否发生或该值已经存在。请参阅 return 值的文档:

1-2) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place.

这是一个常见的模式 -- 您可以使用 insert() 其中 returns 迭代器无论是否添加了某些内容:

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int main()
{
    std::unordered_map<int, string> m;

    auto result = m.insert(std::make_pair(0, "Foo"));

    if(result.second)
       cout << "Inserted: " << result.first->first << " -> " << result.first->second << '\n';

    result = m.insert(std::make_pair(0, "Bar"));

    if(!result.second)
       result.first->second = "Bar";

    for(auto i : m)
       cout << i.first << " -> " << i.second  << '\n';

    return 0;
}

输出:

Inserted: 0 -> Foo
0 -> Bar