NuriKit
v0.1.0b2
Toggle main menu visibility
Loading...
Searching...
No Matches
include
nuri
core
container
compact_map.h
Go to the documentation of this file.
1
//
2
// Project NuriKit - Copyright 2025 SNU Compbio Lab.
3
// SPDX-License-Identifier: Apache-2.0
4
//
5
6
#ifndef NURI_CORE_CONTAINER_COMPACT_MAP_H_
7
#define NURI_CORE_CONTAINER_COMPACT_MAP_H_
8
10
#include <cstddef>
11
#include <type_traits>
12
#include <utility>
13
#include <vector>
15
16
namespace
nuri
{
17
namespace
internal {
18
template
<
class
K,
class
V, V sentinel = -1>
19
class
CompactMap {
20
public
:
21
static_assert
(std::is_convertible_v<K, size_t>,
22
"Key must be an integer-like type"
);
23
24
using
key_type = K;
25
using
mapped_type = V;
26
using
value_type = V;
27
using
size_type = size_t;
28
using
difference_type = ptrdiff_t;
29
using
reference = V &;
30
using
const_reference =
const
V &;
31
using
pointer = V *;
32
using
const_pointer =
const
V *;
33
34
CompactMap(
size_t
cap): data_(cap, sentinel) { }
35
36
template
<
class
... Args>
37
std::pair<pointer, bool> try_emplace(key_type key, Args &&...args) {
38
handle_resize(key);
39
40
reference v = data_[key];
41
bool
isnew = v == sentinel;
42
if
(isnew) {
43
v = V(std::forward<Args>(args)...);
44
}
45
return
{ &v, isnew };
46
}
47
48
pointer find(key_type key) {
49
if
(key < data_.size()) {
50
return
data_[key] == sentinel ? nullptr : &data_[key];
51
}
52
return
nullptr
;
53
}
54
55
const_pointer find(key_type key)
const
{
56
if
(key < data_.size()) {
57
return
data_[key] == sentinel ? nullptr : &data_[key];
58
}
59
return
nullptr
;
60
}
61
62
private
:
63
void
handle_resize(key_type new_key) {
64
if
(new_key >= data_.size()) {
65
data_.resize(new_key + 1, sentinel);
66
}
67
}
68
69
std::vector<V> data_;
70
};
71
}
// namespace internal
72
}
// namespace nuri
73
74
#endif
/* NURI_CORE_CONTAINER_COMPACT_MAP_H_ */
nuri
Definition
crdgen.h:16
Generated by
1.17.0