我有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)时间内查找.
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)
文档提供了更多示例,但它非常易于使用.
使用地图的简便方法
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)
| 归档时间: |
|
| 查看次数: |
17969 次 |
| 最近记录: |