如何从存储pos_struct的map中通过已知last_pos查询对应last_seen值
你给出的示例代码实际为C++代码(C语言无array、map标准容器),以下是具体实现方案:
你当前使用的std::map以int类型为键、pos_struct结构体为值,无法直接通过值内的last_pos字段检索,可根据查询频率选择两种实现方案:
方案1:低频率查询直接遍历
如果只是偶尔查询一次,直接遍历全表匹配即可,因你已保证所有last_pos唯一,匹配到目标后直接返回结果即可,示例代码如下:
#include <array> #include <map> // 要查询的目标坐标 std::array<int, 2> target_pos = {317, 203}; float target_last_seen = 0.0f; bool is_found = false; for (const auto& item : my_map) { const pos_struct& cur = item.second; if (cur.last_pos == target_pos) { target_last_seen = cur.last_seen; is_found = true; break; } } if (is_found) { // 已找到,target_last_seen即为需要的值 } else { // 未找到对应坐标的记录 }
方案2:高频率查询构建反向索引
如果需要频繁执行此类查询,遍历的O(n)时间复杂度效率较低,建议提前构建以last_pos为键的反向索引,将查询时间复杂度降低到O(logn),示例代码如下:
#include <array> #include <map> // 定义反向索引,key为坐标,value为对应last_seen值 std::map<std::array<int, 2>, float> pos_index; // 向原map插入数据时,同步更新反向索引 void add_new_pos(int map_key, float last_seen, std::array<int, 2> pos) { pos_struct new_item; new_item.last_seen = last_seen; new_item.last_pos = pos; my_map[map_key] = new_item; pos_index[pos] = last_seen; } // 查询逻辑 std::array<int, 2> target_pos = {317, 203}; auto it = pos_index.find(target_pos); if (it != pos_index.end()) { float target_last_seen = it->second; // 已找到目标值 } else { // 未找到对应坐标的记录 }
注:std::array本身已重载比较运算符,无需额外自定义比较逻辑即可直接作为std::map的键使用。
内容的提问来源于stack exchange,提问作者polaupa
相关产品推荐
相关产品推荐

