在map/unordered_map中使用find与at

Fra*_*ank 2 c++ containers exception-handling

下面显示了两种查找元素的方法,unordered_map如果所需键的元素不存在,则会引发一些错误条件.他们基本上做同样的事情.是否有理由偏爱另一个,或者仅仅是风格问题?

void foo()
{
    unordered_map<string, int> lookup;

    // Method 1. Lookup using find.
    const auto i = lookup.find("myKey");
    if (i == lookup.end()) {
        // Some error condition...
    }
    else {
        // Do something with i...
    }

    // Method 2. Lookup using try / catch.
    try {
        const auto& ele = lookup.at("myKey");
        // Do something with ele...
    }
    catch (out_of_range& e) {
        // Some error condition...
    }
}
Run Code Online (Sandbox Code Playgroud)

Gal*_*lik 5

就个人而言,我永远不会为这样的事情使用例外.例外是真正特殊的.它们的强大之处在于允许您编写代码而无需进行持续的本地错误检查 但是没有在容器中找到元素(通常)不是错误,它只是两种可能中的一种.

作为一项规则,我会说使用异常,如果没有找到元素意味着你必须中止整个函数/操作/子系统.不要用它来检查单个语句结果.