如何提取unordered_map :: emplace重新调整的对的值?

时间:2018-08-15 15:41:23

标签: c++ unordered-map

我正在尝试使代码短1行,这是一个高尚的原因。我有这张无序的地图

std::unordered_map<std::string, int> um;

并且我想将整数分配给同一行上的变量,在该行上将一对插入到无序映射中,就像这样

int i_want_132_here = um.emplace("hi", 132).first.???;

问题是,我不知道该如何处理[unordered_map :: emplace的返回值]。首先

在调试器中,我可以看到“ first”包含(“ hi”,132),但是如何访问这些值?

1 个答案:

答案 0 :(得分:2)

emplace返回一个pair<iterator, bool>

所以您应该这样做:

int i_want_132_here = (*um.emplace("hi", 132).first).second;

替代语法:

int i_want_132_here = um.emplace("hi", 132).first->second;

通常,我更喜欢使用(*it)而不是it->的形式。