繁体   English   中英

在地图C中迭代和使用find()

[英]Iterating and using find() in a map c++

我有一张地图,其中存储“工作”作为键,存储“名称”作为其存储的值。

map<string, string>dutyAndJob; 
map<string,string>::iterator it; 

我基本上是在尝试通过这张地图查找特定的“名称”。 如果名称不存在,则不应进入此循环,但是由于某些未知原因,它始终会进入此循环:

string name = "Bob";

it = dutyAndJob.find(name);
if (it == dutyAndJob.end())
{
    cout << "Testing : " << name << endl;
}

由于某种原因,即使地图中没有存储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是数据。 您采用的结构化方式只能在Job上使用find来检索Name。

   string job = "Cashier";

   it = dutyAndJob.find(job);
   if (it == dutyAndJob.end())
   {
       cout << "Testing : " << job<< endl;
   }

如果您实际上想按名称搜索,也许名称应该是关键字,而工作应该是数据?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM