避免使用map进行if-else嵌套

时间:2016-07-07 08:50:47

标签: c++

例如我有这样的嵌套

if (scale < 2 ) {turn = "First";
} else if (scale < 5) {turn = "Second";
} else if (scale < 8) {turn = "Third";
}

e.t.c

如何使用映射来避免它,它应该帮助我使用一个if条件。

2 个答案:

答案 0 :(得分:3)

您甚至可以使用简单的排序数组:

struct TurnRank
{
    int rank;
    const char* turn;
};

bool RankComp(int lhs, const TurnRank& rhs) { return lhs < rhs.rank; }

const TurnRank kTurnRank[] = {
    {2, "First"},
    {5, "Second"},
    {8, "Third"},
};

这不需要动态分配,而且非常易读。

现在查找,使用std::upper_bound

#include <algorithm>
#include <iostream>
#include <iterator>

void print_turn(int rank)
{
    auto first = std::begin(kTurnRank), last = std::end(kTurnRank);
    auto it = std::upper_bound(first, last, rank, RankComp);

    if (it == last) std::cout << "Error, rank " << rank << " too large!\n";
    else            std::cout << it->turn << "\n";
}

答案 1 :(得分:0)

我认为,这样的事情可以提供最佳表现:

// Predefined constants.
const char *scaleNames[] = {"First", "First", "Second", "Second",
    "Second", "Third", "Third", "Third"};
const int namesCount = sizeof(scaleNames) / sizeof(*scaleNames);

<...>

turn = (0 <= scale && scale < namesCount) ? scaleNames[scale] : "Unknown";

如果您确定scale始终有效,当然可以省略检查。