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