我想要一个函数,该函数在 map 的集合 中搜索一个键,并将迭代器返回到找到的键。但是如果找不到 key 应该返回什么?我无法返回 map::end,因为 map 集合可能为空。
谢谢。
map<string, string>::iterator CConfFile::GetKey(const string &SectionName, const string &KeyName)
{
maps<string, map<string, string> >::const_iterator Section = _Sections.find(SectionName);
if (Section != _Sections.end()) {
map<string, string> &Keys = SectionPtr->second;
map<std::string, string>::const_iterator Key = Keys.find(KeyName);
if (Key != Keys.end())
return Key;
}
cerr << "Key " << KeyName << "not found\n";
return WHAT???;
}
最佳答案
如果您返回一个迭代器,则意味着实际上可以迭代所有值。如果情况确实如此,则无论如何您都必须返回自定义迭代器类型,并且表示特殊的结束迭代器应该没有问题。
如果迭代器不打算用作迭代器,最好返回一个指向找到的对象的指针,并在没有任何指针的情况下返回一个空指针。
关于c++ - 为不存在的 map 返回什么迭代器如何签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681709/