eis/TestProject/play_gruond/mapUpdater.hpp

51 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <map>
#include <string>
#include <unordered_map>
#include <vector>
class MapUpdater {
public:
std::map<std::string, double> data;
// 初始化:预建立迭代器缓存(只执行一次)
void init(const std::vector<std::string> &ordered_keys) {
// 先插入所有 key确保存在
for (const auto &key : ordered_keys) {
data[key] = 0.0;
}
// 预缓存迭代器
iter_cache.reserve(ordered_keys.size());
for (const auto &key : ordered_keys) {
iter_cache[key] = data.find(key);
}
ordered_keys_ = ordered_keys;
}
// 高效更新(每 50ms 调用):无需查找,直接写值
void update(const std::string &key, double value) {
auto it = iter_cache.find(key);
if (it != iter_cache.end()) {
it->second->second = value;
}
}
// 按固定顺序刷新全部(批量模式)
void refresh_all(const std::vector<double> &values) {
for (size_t i = 0; i < ordered_keys_.size(); ++i) {
iter_cache[ordered_keys_[i]]->second = values[i];
}
}
// 按固定顺序遍历
void for_each_ordered(std::function<void(const std::string &, double)> fn) {
for (const auto &key : ordered_keys_) {
fn(key, data[key]);
}
}
private:
std::vector<std::string> ordered_keys_;
std::unordered_map<std::string, std::map<std::string, double>::iterator>
iter_cache;
};