[英]How to find the value for a key in unordered map?
I am trying to do the below sample in unordered map in c++我正在尝试在 c++ 中的无序 map 中执行以下示例
my_dict = {'one': ['alpha','gamma'], 'two': ['beta'], 'three' : ['charlie']}
print(my_dict["one"]) // ['alpha','gamma']
I tried using find
operator like below我尝试使用如下的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;
}
But I am not able to retrieve the value for this key dict["one"]
.但我无法检索此键dict["one"]
的值。 Am i missing anything?我错过了什么吗? Any help is highly appreciated.非常感谢任何帮助。 Thanks谢谢
This is because your it->first
will point to the key of the dictionary ie "One" and it->second
will point to the value ie the vector.这是因为您的it->first
将指向字典的键,即“One”,而it->second
将指向值,即向量。
So to print elements of the vector you need to specify the indexes of the vector that you are printing as well.因此,要打印向量的元素,您还需要指定要打印的向量的索引。 The following code will give you the result you want:以下代码将为您提供所需的结果:
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[0]<<it->second[1]<<endl; // expected output alphabeta
return 0;
} }
PS Please accept my answer if you find it useful as that would help me get some reputation points PS如果您觉得它有用,请接受我的回答,因为这将帮助我获得一些声誉积分
The failure you are encountering is due to it->second
being a std::vector
object, which cannot be printed to std::cout
because it lacks an overload for operator<<(std::ostream&,...)
.您遇到的失败是由于 it- it->second
是std::vector
object,它无法打印到std::cout
因为它缺少operator<<(std::ostream&,...)
的重载。
Unlike languages like Python that do this for you, in C++ you must manually loop through the elements and print each entry.与 Python 等为您执行此操作的语言不同,在 C++ 中,您必须手动循环遍历元素并打印每个条目。
To fix this, you will need to change this line:要解决此问题,您需要更改此行:
cout<<it->second<<endl; // expected output alphabeta
To instead print each object in the container.改为打印容器中的每个 object。 This could be something simple like looping through all elements and printing them:这可能很简单,比如遍历所有元素并打印它们:
for (const auto& v : it->second) {
std::cout << v << ' '; // Note: this will leave an extra space at the end
}
std::cout << std::endl;
Or you can go more complex if the exact formatting is important.或者,如果确切的格式很重要,您可以使用更复杂的 go。
@DanielLangr posted a link in the comments to the question that summarizes all possible ways of doing this, and I recommend taking a look if you're wanting anything more complex: How do I print the contents to a Vector? @DanielLangr 在该问题的评论中发布了一个链接,该链接总结了所有可能的方法,如果您想要更复杂的内容,我建议您查看一下:如何将内容打印到 Vector?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.