我使用以下代码在我的earlier question中提到了string
和类型Person
之间的映射。
std::map<std::string, Person*> person_list;
// while...
Person* person = University::addInput(person_type, person_name); //person_type: EMPLOYEE, ALUMNI, STUDENT
person_list[person_name] = person;
问题:如果Person type
为ALUMNI
,那么它应该与另一个STUDENT
类型的人联系,他的名字已被映射之前。现在,我想连接这两个人。
我正在尝试找到student_name
(这是此映射方案中的关键字)但不了解正确的方法。
PS:为了消除不必要的混淆,我删除了find()
问题。我真正的任务是找到给定键的映射对象。所以,我认为find()可以帮助我。但如果还有其他一些方法......请建议我
答案 0 :(得分:2)
你真正想写的是这样的:if(person_list.find("Tim") == person_list.end())
。 find
返回一个无法隐式转换为bool
的交互器。
答案 1 :(得分:1)
if(person_list.find("Tim")) // == node_list.end()
上述行不正确。 find的结果是迭代器。该错误告诉您它无法隐式地将迭代器转换为bool。您需要将其与地图的结束迭代器进行比较。当然,在这之后你会得到cout,因为很明显地图中没有名叫Tim的人。
答案 2 :(得分:0)
有两种方法可以实现您的目标:
在地图中查找"Tim"
。如果找到,请将其输出到cout
。
std::map<std::string, char>::iterator found = person_list.find("Tim");
if ( found != person_list.end() )
{
std::cout << found->second << std::endl;
}
假设地图中存在"Tim"
,并使用[]
运算符访问其值。
std::cout << person_list["Tim"] << std::endl;
答案 3 :(得分:0)
您可以使用map.at()
的内置边界检查来获益:
try{
Person* tim = person_list.at("Tim");
/* do stuff with tim */
}
catch(const std::out_of_range& e){
std::cout << "Tim not found!" << std::endl;
}