gpt4 book ai didi

c++ - 如何提取 unordered_map::emplace 返回的 pair 的值?

转载 作者:行者123 更新时间:2023-11-28 01:30:14 27 4
gpt4 key购买 nike

我正在努力缩短我的代码 1 行,这是一项崇高的事业。我有这张无序 map

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

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

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

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

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

最佳答案

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-> .

关于c++ - 如何提取 unordered_map::emplace 返回的 pair 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51861973/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com