如何将int映射到C/C++中的相应字符串

yan*_*nce 4 c c++ qt

我有20位数字,我想将它们与字符串相关联.除了使用switch case语句实现这一点之外,还有更快的方法吗?

我需要将int转换为相应的字符串,并且数字不一定是打包的.一些代码Qt也可能有用吗?

示例:以下数字和字符串相互关联,

1:   "Request System Info"

2:   "Change System Info"

10:  "Unkown Error"
Run Code Online (Sandbox Code Playgroud)

R S*_*hko 18

我推荐std :: map <>

#include <map>
#include <string>

std::map<int, std::string> mapping;

// Initialize the map
mapping.insert(std::make_pair(1, "Request System Info"));
mapping.insert(std::make_pair(2, "Change System Info"));
mapping.insert(std::make_pair(10, "Unkown Error"));

// Use the map
std::map<int, std::string>::const_iterator iter =
    mapping.find(num);
if (iter != mapping.end())
{
    // iter->second contains your string
    // iter->first contains the number you just looked up
}
Run Code Online (Sandbox Code Playgroud)

如果您的编译器实现了C++ 0x标准草案initalizer-list功能,那么您可以组合地图的定义和初始化:

std::map<int, std::string> mapping = {{1, "Request System Info"},
                                      {2, "Change System Info"}
                                      {10, "Unkown Error"}};
Run Code Online (Sandbox Code Playgroud)

std :: map <>可以很好地扩展到大量条目,因为std :: map <> :: find在O(log N)中运行.一旦你拥有草案C++ 0x标准哈希映射功能,你就可以轻松地将它转换为std :: unordered_map <>,它应该能够在O(1)时间内查找.

  • @yan - std :: map是标准C++库的一部分,因此它可以与任何兼容的编译器一起使用. (2认同)
  • 不,那是STL. (2认同)

Rob*_*Rob 7

Qt还提供了它自己的地图实现- QMAPQHash.

QMap<int, QString> myMap;
myMap[1234] = "Some value";
myMap[5678] = "Another value";
Run Code Online (Sandbox Code Playgroud)

要么

myMap.insert(1234, "Some value");
Run Code Online (Sandbox Code Playgroud)

文档提供了更多示例,但它非常易于使用.


pm1*_*100 5

使用地图的简便方法

std::map<int, std::string> mymap;
mymap[1] = "foo";
mymap[10] = "bar";
// ...
int idx = 10;
std::string lookup = mymap[idx];
Run Code Online (Sandbox Code Playgroud)

  • 使用operator []进行查找的一个问题是,如果您要查找的索引不在地图中,它将修改您的地图。 (3认同)