代码之家  ›  专栏  ›  技术社区  ›  kolrie

ARDUINO C++中的字典式数据结构

  •  2
  • kolrie  · 技术社区  · 6 年前

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

    这里,0x29是密钥的USB代码,因此这是字典查找的密钥。然后,我会使用 entry.name 出于调试目的, entry.make 是按键(keyDown)时需要发送的字节数组,并且 entry.break 释放钥匙时(钥匙向上)。

    在C++中,实现这个目标的方法是什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Ted Lyngmo    6 年前

    看起来像 ArduinoSTL 1.1.0 不包括 unordered_map map 这样地。

    1. 下载Arduino STL 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());
    }