0

我试图让我的代码 1 行更短,这是一个崇高的事业。我有这张无序的地图

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

我想将整数分配给同一行上的一个变量,我将一对放入无序映射中,就像这样

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

问题是,我不知道如何处理 [return value of unordered_map::emplace].first

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

4

1 回答 1

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)form 而不是it->.

于 2018-08-15T15:46:12.793 回答