首页 > 解决方案 > 使用标称值索引而不是字符串值

问题描述

我正在研究以文本格式(来自文本文件或缓冲区)接收离散值的实时系统。我需要收集统计数据并对这些值进行其他数值处理,为了加快速度,我正在考虑使用整数(例如索引)而不是std::string.

Allowed Values:
Black, Red, Green
After transformation:
0,1,2 (respectively)

我还想控制无效值,例如yellow将无效,因为它不是允许的值。

所以在任何时候t,我都会收到这个值,需要将它解析为它的索引,然后使用它。警告:延迟非常重要,我需要它尽可能快。

哪一种是实现这一点的合适的高性能方式?

标签: c++performancedata-structuresc++17

解决方案


如果速度很重要,那么查找表总是一个快速的解决方案。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;
}

推荐阅读