在map中迭代并使用find()
Iterating and using find() in a map c++
我有一个映射,将"job"存储为键,并将"name"存储为值。
map<string, string>dutyAndJob;
map<string,string>::iterator it;
我基本上试图通过这张地图寻找一个特定的"名字"。如果名字不存在,它不应该进入这个循环,然而,由于某些未知的原因,它总是进入这个循环:
string name = "Bob";
it = dutyAndJob.find(name);
if (it == dutyAndJob.end())
{
cout << "Testing : " << name << endl;
}
由于某种原因,即使map中没有存储Bob,它仍然会进入这个循环。
任何帮助都将非常感激!
if (it == dutyAndJob.end())
{
cout << "Testing : " << name << endl;
}
应:if (it != dutyAndJob.end()) // Does it refer to a valid association
{
cout << "Testing : " << name << endl;
}
注意从==
到!=
的变化,表明在映射中找到了键。只有当没有时,迭代器it
才等于dutyAndJob.end()
。
刚刚意识到Job是键,Name是数据。按照您的结构化方式,您只能在将检索Name的作业上使用find。
string job = "Cashier";
it = dutyAndJob.find(job);
if (it == dutyAndJob.end())
{
cout << "Testing : " << job<< endl;
}
如果你真的想通过Name搜索,也许Name应该是键,而Job应该是数据?
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 为什么std::map有find成员函数
- 在libc++和libstdc++之间的std::map上使用std::find时的实现差异
- std::map::find 的效率是否与值的数据大小有关?
- 有没有办法从map::find()获得提升::可选结果?
- Map.find()如何工作,查看输出的组件
- 如何在map::find()函数中引用类元素?
- C++ map::find() in stl
- C++ std::map::find to C# 字典<键,val>
- C++ STL: std::find with std::map
- 为什么要对 map::find 应用不存在的键将返回一个C++中第一个值映射大小的迭代器
- map.find() 找不到键 C++
- std::map中的find()函数返回一个值,尽管没有有效的键
- std :: map find()返回错误
- 为什么没有针对STD :: MAP的find/lower_bound过载,而STD :: list没有排序的过载
- 重载 map::key_comp,以便我可以在对象指针的地图上使用 map::find
- issue with std::map std::find
- c++ STL map::find()