c++ - 为不存在的 map 返回什么迭代器如何签名?

标签 c++ stl dictionary

我想要一个函数,该函数在 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/

相关文章:

python - 如何从文件中读取两行并在 for 循环中创建动态键?

c++ - 如何在 map 的 map 上使用 map::find

c++ - 如何在 C++ 中使用常量数组的成员函数?

c++ - 在 C++ 中寻找 MemoryStream

c++ - 为什么有两种 std::sort 实现(带和不带比较器)而不是带默认模板参数的一种实现?

dictionary - 将映射值复制到指针的结构

python - 为什么我的表单试图提交到错误的端点?

c++ - boost named_condition 实现

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - 如何创建一个类来接受包含任何类型数据的 vector ?