c++ - 如何找到unordered_map中某个键的值?

标签 c++ unordered-map

我正在尝试在 C++ 中的无序映射中执行以下示例

my_dict = {'one': ['alpha','gamma'], 'two': ['beta'], 'three' : ['charlie']}
print(my_dict["one"]) // ['alpha','gamma']

我尝试使用 find 运算符,如下所示

int main ()
{
std::unordered_map<std::string, std::vector<std::string>> dict;
dict["one"].push_back("alpha");
dict["one"].push_back("beta");
dict["two"].push_back("gamma");
 auto it = dict.find("one");
 cout<<it->second<<endl; // expected output alphabeta
return 0;
}

但我无法检索此键 dict["one"] 的值。我错过了什么吗? 非常感谢任何帮助。 谢谢

最佳答案

您遇到的失败是由于 it->secondstd::vector对象,无法打印到 std::cout因为它缺少 operator<<(std::ostream&,...) 的重载.

与 Python 等为您执行此操作的语言不同,在 C++ 中,您必须手动循环遍历元素并打印每个条目。

要解决此问题,您需要更改此行:

 cout<<it->second<<endl; // expected output alphabeta

改为打印容器中的每个对象。这可能很简单,例如循环遍历所有元素并打印它们:

for (const auto& v : it->second) {
    std::cout << v << ' '; // Note: this will leave an extra space at the end
}
std::cout << std::endl;

或者,如果精确的格式很重要,您可以变得更复杂。


@DanielLangr 在问题的评论中发布了一个链接,总结了所有可能的方法,如果您想要更复杂的内容,我建议您看一下:How do I print the contents to a Vector?

关于c++ - 如何找到unordered_map中某个键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66039319/

相关文章:

c++ - 当 "moved"对象在 union 中有一个 "non-trivial"成员时,为什么要强制复制构造函数?

c++ - 返回时复制操作是在 lock_guard 析构函数之前还是之后执行的?

c++ - 是否可以使用非常量键类型的 unordered_map?

c++ - 在Windows中编译OpenSSL-生成的LIB为DLL文件使用了错误的名称

C++模板非类型参数类型推导

c++ - C++ unordered_map emplace()函数抛出seg错误,我也不知道为什么

c++ - std::unordered_map 的桶数意外增长

c++ - 通过静态局部变量的引用/指针返回

c++ - 遍历容器——何时使用引用,何时不使用

c++ - 在 gdb 中使用 [] 运算符和 unordered_map 给出未解析的运算符