与 this example作为我最了解如何使用 C++ 搜索 map 的方法,我仍然需要帮助。
我为电话簿创建了 map 。
map<string,int> PhBook;
现在我让用户向其中添加姓名和电话。
getline(cin >> ws,name);
cin >> phone;
PhBook[name] = phone;
我想做的是让用户在 map 中搜索可能的名称并相应地打印“电话 = ....”或“未找到”消息。
那我该怎么做呢?因为我是新手,所以我想要最简单的解决方案。我的困难在于我不知道如何使用元素(人名)搜索 map 。
最佳答案
这里 map 返回一个迭代器到 it
如果找到,否则 it
返回一个迭代器到 map::end
map<string,int> ::iterator it;
it = PhBook.find(name);
if (it != PhBook.end()){
cout<<"The phone = "<<it->second<<endl;
}else{
cout<<"Not found"<<endl;
}
关于c++ - 如何在 C++ 中搜索 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42477384/