小编Fra*_*ank的帖子

C++ 中的多个返回语句和性能

就性能而言,是否有任何理由支持函数中的单个返回语句而不是多个返回语句?

考虑下面的简单例子。

int min(int a, int b)
{
    if (a < b)
        return a;

    return b;
}

int min2(int a, int b)
{
    int result;

    if (a < b)
        result = a;
    else
        result = b;

    return result;
}

enum class Fruit { Apple, Orange, Banana };
std::string fruitToString(Fruit f)
{
    switch (f)
    {
        case Fruit::Apple:
            return "Apple";
        case Fruit::Orange:
            return "Orange";
        case Fruit::Banana:
            return "Banana";
        default:
            return "Unknown Fruit";
    }
}

std::string fruitToString2(Fruit f)
{
    std::string result;

    switch (f) …
Run Code Online (Sandbox Code Playgroud)

c++ performance

5
推荐指数
1
解决办法
1440
查看次数

在map/unordered_map中使用find与at

下面显示了两种查找元素的方法,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)

c++ containers exception-handling

2
推荐指数
1
解决办法
1088
查看次数

标签 统计

c++ ×2

containers ×1

exception-handling ×1

performance ×1