无法在ArduinoSTL的std::map中使用ArduinoJSON解析的数据
ArduinoJSON解析JSON并存入ArduinoSTL的std::map报错问题
JSON文档结构
{ "type":"init", "anchors": [ { "id": "xyz", "loc": { "x": 10, "y": 30 } } ... ] }
现有代码定义
Location类与全局map
class Location { public: int x; int y; Location() : x(0), y(0) {} Location(int x, int y) : x(x), y(y) {} }; std::map<String, Location> anchors{};
解析函数实现
最初的函数写法:
void AP_init(const JsonDocument& doc) { const JsonArray& arr = doc["anchors"].as<JsonArray>(); for (const JsonObject anchor : arr) { // 尝试过insert_or_assign但未找到该函数 anchors.insert(anchor["id"].as<const char*>(), Location(anchor["loc"]["x"].as<int>(), anchor["loc"]["y"].as<int>()) ); } }
报错情况
- 首次报错:
error: no matching function for call to 'std::map<String, Location>::insert(ArduinoJson6194_F1::enable_if<true, const char*>::type, Location)'
- 修改为String变量后仍报错:
String id = anchor["id"]; anchors.insert(id, Location(anchor["loc"]["x"].as<int>(), anchor["loc"]["y"].as<int>()) );
报错信息:
error: no matching function for call to 'std::map<String, Location>::insert(String&, Location)'
- 简化代码测试依旧报错:
anchors.insert(String(), Location() );
报错信息:
error: no matching function for call to 'std::map<String, Location>::insert(String, Location)'
推测Arduino的STL实现存在功能缺失。
解决方法
问题核心是std::map的insert方法并不支持直接传入(key, value)两个独立参数,无论标准STL还是ArduinoSTL都是如此。你有两种可行方案:
方案1:使用std::pair构造键值对传入insert
void AP_init(const JsonDocument& doc) { const JsonArray& arr = doc["anchors"].as<JsonArray>(); for (const JsonObject anchor : arr) { String id = anchor["id"].as<String>(); Location loc(anchor["loc"]["x"].as<int>(), anchor["loc"]["y"].as<int>()); anchors.insert(std::make_pair(id, loc)); // 或者用emplace直接构造pair,更高效 // anchors.emplace(id, loc); } }
方案2:使用map的[]运算符(更简洁,支持更新/插入)
因为你需求是更新或插入锚点数据,map的[]运算符会自动处理:如果key已存在则覆盖原有value,不存在则插入新键值对,完全符合需求:
void AP_init(const JsonDocument& doc) { const JsonArray& arr = doc["anchors"].as<JsonArray>(); for (const JsonObject anchor : arr) { String id = anchor["id"].as<String>(); anchors[id] = Location(anchor["loc"]["x"].as<int>(), anchor["loc"]["y"].as<int>()); } }
关于insert_or_assign
ArduinoSTL通常基于C11或C14的子集,而insert_or_assign是C++17引入的方法,所以确实无法使用,用上述方案2的[]运算符可以替代其功能。
内容的提问来源于stack exchange,提问作者CarbonMan
相关产品推荐
相关产品推荐

