I want to have a function which searches for a key in a collection of maps and returns an iterator to the found key. But what should be returned in case the key cannot be found? I cannot return map::end since the collection of maps can be empty.
Thanks.
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???;
}
If you return an iterator, then that implies that one can actually iterate over all the values. If thats indeed the case, you would have to return a custom iterator type anyway and you should have no problem to denote a special end iterator.
If the iterator isn’t intended to be used as an iterator, it might be better to return a pointer to the found object, and a null pointer in case there isn’t any.