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

3

我正在使用Arduino编写USB到PS/2转换器,并且有一个数据结构,如果我使用其他高级语言,我会像实现字典一样来实现它。输入的格式可能如下:

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

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

在 C++ 中实现这一点的方法是什么?


一堆枚举和 switch 语句怎么样? - The Quantum Physicist
2
std::map<unsigned int, MyStructure>? - rustyx
关于@rustyx的笔记,您可以参考以下链接:https://forum.arduino.cc/index.php?topic=87778.0 ,同时也可以考虑https://arduinojson.org/(不过它似乎会比std::map更耗费资源)。 - George Profenza
1个回答

3

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

  1. 下载 Arduino STL ZIP 文件并将其放在方便的位置
  2. Sketch\Include Library\Add ZIP library 并给它 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());
}

我遇到了多个编译错误:https://gist.github.com/fcoury/cab3fbc3a8fdc40f109475e5320b36de - kolrie
我试试能否启动我的Arduino环境。多年没有使用过,也从未在其中使用过STL。会很有趣 :-) - Ted Lyngmo
非常感谢。我正在更新Gist,加入我正在尝试的新内容。谢谢! - kolrie
我想我懂了!请查看这个新的代码片段:https://gist.github.com/fcoury/623d3d0ce9be0dddba80779172b9e51e - kolrie
1
太好了!我刚刚意识到我提出的初始化方法有点笨拙,所以我刚刚编辑了一下,展示了一个更简单的方式(虽然我不知道我放进去的数字是否正确)。 - Ted Lyngmo
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接