From a8015244cb265fadd537767228980532bf582b98 Mon Sep 17 00:00:00 2001 From: NaiJi Date: Thu, 11 Apr 2024 00:52:00 +0400 Subject: [PATCH] add time value map --- cpp/time_value_map.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 cpp/time_value_map.cpp diff --git a/cpp/time_value_map.cpp b/cpp/time_value_map.cpp new file mode 100644 index 0000000..44467e4 --- /dev/null +++ b/cpp/time_value_map.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +template +class TimeValueMap +{ +public: + void set(const K& key, const V& value, int timestamp) + { + _map[key][timestamp] = value; + } + + V get(const K& key, int timestamp) + { + const auto values = _map.find(key); + if (values == _map.end()) + { + return V(); + } + + const auto& values_map = values->second; + auto value = values_map.lower_bound(timestamp); + if (value == values_map.end()) + { + if (timestamp > values_map.rbegin()->first) + { + return values_map.rbegin()->second; + } + + return V(); + } + + if (value->first != timestamp) + { + if (value == values_map.begin()) + { + return V(); + } + + value--; + } + + return value->second; + } + +private: + std::map> _map; +}; + +int main() +{ + TimeValueMap map; + //map.set("a", "1", 1); + map.set("a", "2", 2); + map.set("a", "5", 5); + std::cout << map.get("a", 10) << '\n'; +} \ No newline at end of file