add time value map

This commit is contained in:
NaiJi ✨ 2024-04-11 00:52:00 +04:00
parent c7d2b6269c
commit a8015244cb
1 changed files with 58 additions and 0 deletions

58
cpp/time_value_map.cpp Normal file
View File

@ -0,0 +1,58 @@
#include <iostream>
#include <vector>
#include <map>
template <typename K, typename V>
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<K, std::map<int, V>> _map;
};
int main()
{
TimeValueMap<std::string, std::string> map;
//map.set("a", "1", 1);
map.set("a", "2", 2);
map.set("a", "5", 5);
std::cout << map.get("a", 10) << '\n';
}