c++ - 使用标称值索引而不是字符串值
问题描述
我正在研究以文本格式(来自文本文件或缓冲区)接收离散值的实时系统。我需要收集统计数据并对这些值进行其他数值处理,为了加快速度,我正在考虑使用整数(例如索引)而不是std::string
.
Allowed Values:
Black, Red, Green
After transformation:
0,1,2 (respectively)
我还想控制无效值,例如yellow
将无效,因为它不是允许的值。
所以在任何时候t
,我都会收到这个值,需要将它解析为它的索引,然后使用它。警告:延迟非常重要,我需要它尽可能快。
哪一种是实现这一点的合适的高性能方式?
解决方案
如果速度很重要,那么查找表总是一个快速的解决方案。C++ 提供了关联容器。
地图是一个合适的解决方案。
请参见以下示例:
#include <string>
#include <map>
#include <iostream>
using KeyType = std::string;
using LookUpValue = int;
using LookUpTable = std::map<KeyType,LookUpValue>;
LookUpTable lookUpTable {{"Black",1}, {"Red",2}, {"Green",3}};
constexpr LookUpValue InvalidInput{0};
inline LookUpValue convertTextToKey(const std::string& text)
{
return (lookUpTable.end()==lookUpTable.find(text)) ? InvalidInput : lookUpTable[text];
}
int main()
{
std::cout << convertTextToKey("Nonsense") << ' ' << convertTextToKey("Black") << ' '
<< convertTextToKey("Red") << ' ' << convertTextToKey("Green") << '\n';
return 0;
}
推荐阅读
- amazon-ec2 - 将来自不同主机的多个IP地址指向具有不同端口的相同域名
- autohotkey - 自动热键映射修改器
- java - 我不明白在这种情况下线程是如何工作的
- python - 如何在将 pandas 用于 csv 文件时更改不同数据类型的标记样式
- amazon-web-services - lambda 代理集成 cognitoIdentityId
- python - 将 3 维 numpy 数组压缩为 2 维
- image - 如何在 MatLab 或 Photoshop 中将扫描图像的白色部分变白并将黑色部分变黑
- r - 在 R 中:选择行中数值的数据框函数中的列
- python - 如何判断 Python 程序是否正在运行而无需等待它完成?
- java - 更改实体字段时如何使 HSQL 不自动更新实体