Add util::unique_sequential_storage for storing an array of unique elements
This commit is contained in:
parent
f27a4fa26d
commit
58215fedc1
1 changed files with 37 additions and 0 deletions
37
libs/util/include/psemek/util/unique_sequential_storage.hpp
Normal file
37
libs/util/include/psemek/util/unique_sequential_storage.hpp
Normal 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_;
|
||||
};
|
||||
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue