Add util::unique_sequential_storage for storing an array of unique elements

This commit is contained in:
Nikita Lisitsa 2023-08-19 15:20:57 +03:00
parent f27a4fa26d
commit 58215fedc1

View file

@ -0,0 +1,37 @@
#pragma once
#include <unordered_map>
#include <vector>
#include <cstdint>
namespace psemek::util
{
template <typename T, typename Hash = std::hash<T>>
struct unique_sequential_storage
{
using index = std::uint32_t;
template <typename H>
index insert(H && value)
{
if (auto it = value_to_index_.find(value); it != value_to_index_.end())
return it->second;
index result = index_to_value_.size();
index_to_value_.push_back(value);
value_to_index_[std::forward<H>(value)] = result;
return result;
}
T const & get(index i) const
{
return index_to_value_[i];
}
private:
std::unordered_map<T, index, Hash> value_to_index_;
std::vector<T> index_to_value_;
};
}