C ++ Long switch语句或查找地图? [英] C++ Long switch statement or look up with a map?

查看:176
本文介绍了C ++ Long switch语句或查找地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++应用程序中,我有一些值作为代码来表示其他值。为了翻译代码,我一直在辩论使用switch语句或stl地图。切换将如下所示:

In my C++ application, I have some values that act as codes to represent other values. To translate the codes, I've been debating between using a switch statement or an stl map. The switch would look something like this:

int code;
int value;
switch(code)
{
case 1:
    value = 10;
    break;
case 2:
    value = 15;
    break;
}

映射将是 stl :: map< int,int> 并且翻译将是一个简单的查找代码用作键值。

The map would be an stl::map<int, int> and translation would be a simple lookup with the code used as the key value.

哪一个更好/更高效/清洁/接受?为什么?

Which one is better/more efficient/cleaner/accepted? Why?

推荐答案

就我个人而言,我会使用地图,因为它的用途意味着数据查找 - 在程序行为。此外,使用映射比使用开关更容易修改数据映射。

Personally, I would use the map, as its use implies a data lookup - using a switch usually indicates a difference in program behavior. Furthermore modifying the data mapping is easier with a map than with a switch.

如果性能是一个真正的问题,分析是获得可用答案的唯一方法。如果分支错误预测经常发生,开关可能不会更快。

If performance is a real issue, profiling is the only way to get a usable answer. A switch may not be faster if branch mispredictions happen often enough.

另一种想法是,如果将代码和相关联的值转换为数据结构,特别是如果代码和值的范围是静态的:

Another approach to think about this is if it wouldn't make more sense to combine the code and the associated value into a datastructure, especially if the range of codes and values is static:

struct Code { int code; int value; };

Code c = ...

std::cout << "Code " << c.code << ", value " << c.value << std::end;

这篇关于C ++ Long switch语句或查找地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆