【问题标题】:Use index of nominal values instead of a string value使用标称值索引而不是字符串值
【发布时间】:2018-11-16 21:33:26
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 我会使用 io 流的标准方法,看看我是否满足时间要求。如果你从 HDD 甚至 SSD 读取,你可能会被 IO 束缚。
  • 我可以从文件系统以外的其他来源获取,并且到达率很高。但我对如何将字符串映射到 int 更感兴趣。 std::map 似乎有点矫枉过正,如果有其他选择,我正在徘徊。

标签: c++ performance data-structures c++17


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多