在map中迭代并使用find()

Iterating and using find() in a map c++

本文关键字:find map 迭代      更新时间:2023-10-16

我有一个映射,将"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应该是数据?