20#ifndef UTILS_ENUMERATED_CONTAINER_HPP
21#define UTILS_ENUMERATED_CONTAINER_HPP
30#include <unordered_map>
43 typedef typename std::unordered_map<index_type, T>::iterator
iterator;
46 typedef typename std::unordered_map<index_type, T>::value_type
value_type;
49 m_free_indices.insert(0);
50 m_free_indices.insert(1);
59 for (
auto const &e : l) {
60 m_container[e.first] = e.second;
62 if (
auto it = m_free_indices.find(e.first); it != m_free_indices.end()) {
63 m_free_indices.erase(it);
68 for (index_type it(0); m_free_indices.size() < 2; ++it) {
69 if (m_container.find(it) == m_container.end()) {
70 m_free_indices.insert(it);
82 index_type
add(
const T &c) {
83 const index_type ind = get_index();
89 index_type
add(T &&c) {
90 const index_type ind = get_index();
91 m_container[ind] = std::move(c);
105 assert(m_container.find(i) != m_container.end());
107 m_container.erase(i);
108 m_free_indices.insert(i);
125 const T &
operator[](index_type i)
const {
return m_container.at(i); }
163 std::size_t
size()
const {
return m_container.size(); }
167 std::unordered_map<index_type, T> m_container;
169 std::set<index_type> m_free_indices;
183 index_type get_index() {
186 assert(!m_free_indices.empty());
187 const index_type index = *m_free_indices.begin();
189 m_free_indices.erase(index);
193 if (m_free_indices.size() == 1) {
194 m_free_indices.insert(*(--m_free_indices.end()) + 1);
Container for objects that are identified by a numeric id.
std::unordered_map< index_type, T >::iterator iterator
const_iterator find(int id) const
find object by id.
const T & operator[](index_type i) const
Get element from container.
std::unordered_map< index_type, T >::const_iterator const_iterator
iterator find(int id)
find object by id.
index_type add(const T &c)
Copy c into the container.
const_iterator begin() const
Get a const iterator to beginning of the container.
void remove(index_type i)
Remove element from container.
iterator end()
Get an iterator to end of the container.
const_iterator end() const
Get a const iterator to end of the container.
std::unordered_map< index_type, T >::value_type value_type
index_type add(T &&c)
This is an overloaded member function, provided for convenience. It differs from the above function o...
iterator begin()
Get iterator to beginning of the container.
NumeratedContainer(std::initializer_list< value_type > l)
Construct from list of key-value pairs.
T & operator[](index_type i)
Get element from container.