c++ - Arduino C++ 中类似字典的数据结构

标签 c++ data-structures arduino

我正在 Arduino 中编写一个 USB 到 PS/2 转换器,我有一个数据结构,如果我使用另一种高级语言,我会像字典一样实现它。条目将类似于:

{ 0x29: { name: "esc", make: [0x76], break: [0xfe, 0x76] } }

此处,0x29 是 key 的 USB 代码,因此这是此字典查找的 key 。然后,我将使用 entry.name 进行调试,entry.make 是我需要在按下键 (keyDown) 和 时发送的字节数组entry.break 当键被释放时(keyUp)。

用 C++ 实现这个的方法是什么?

最佳答案

看起来像ArduinoSTL 1.1.0不包含 unordered_map,因此您可以像这样创建一个 map

  1. 下载 Arduino STL ZIP 文件并将其放在合适的地方
  2. Sketch\Include Library\Add ZIP 库并为其提供 ZIP 文件的完整路径。

那么这应该可以编译,尽管有很多关于未使用变量的 STL 警告。

#include <ArduinoSTL.h>    
#include <iostream>
#include <string>
#include <map>

struct key_entry {
    std::string name;
    std::string down;
    std::string up;
    key_entry() : name(), down(), up() {}
    key_entry(const std::string& n, const std::string& d, const std::string& u) :
        name(n),
        down(d),
        up(u)
    {}
};

using keydict = std::map<unsigned int, key_entry>;

keydict kd = {
    {0x28, {"KEY_ENTER",  "\x5a", "\xf0\x5a"}},
    {0x29, {"KEY_ESC",    "\x76", "\xf0\x76"}}
};

void setup() {
    Serial.begin( 115200 );  
}

void loop() {
    auto& a = kd[0x29];
    // use a.down or a.up (or a.name for debugging)
    Serial.write(a.up.c_str(), a.up.size());
}

关于c++ - Arduino C++ 中类似字典的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498564/

相关文章:

c++ - 类命名空间内的模板特化

c++ - 通过引用参数和指针传递

c - 为什么我从代码中带有位域的 C union 获得此输出?

php - 在我的数据库中构建 "pages"的启用和排列

function - 使用Arduino淡入多个LED

C++ 递减单字节( volatile )数组的元素不是原子的!为什么? (还有 : how do I force atomicity in Atmel AVR mcus/Arduino)

c++ - 在重定向stdout和stderr之前保存日志

c++ - 矩阵乘法

c++ - DAWG 可以用来存储单词相关信息吗?

c++ - 如何摆脱这个 Do-While 循环?