KisaragiLibrary
 
読み取り中…
検索中…
一致する文字列を見つけられません
SparseSet.hpp
[詳解]
1#pragma once
2
3#include <vector>
4#include <unordered_map>
5
6
7namespace Kisaragi_Lib
8{
9 /// <summary>
10 ///
11 /// </summary>
12 /// <typeparam name="Key"></typeparam>
13 /// <typeparam name="Value"></typeparam>
14 template<class Key, class Value>
16 {
17 private:
18 /// <summary>
19 /// 疎な配列、keyを引数としてvalue配列の引数を取得する
20 /// </summary>
21 std::unordered_map<Key, unsigned int>sparseContainer;
22
23 /// <summary>
24 /// 密な配列、実際のバリューが格納される
25 /// </summary>
26 std::vector<Value>denseContainer;
27
28 /// <summary>
29 /// denseをループ処理するときにkeyがほしい時などに使うやつ
30 /// </summary>
31 std::vector<Key>indexToKey;
32 public:
33
34 /// <summary>
35 /// 配列の追加
36 /// </summary>
37 /// <param name="_key">配列のKey</param>
38 /// <param name="_value">配列の要素</param>
39 void Add(const Key& _key, const Value& _value)
40 {
41 // Keyが重複している場合は、返す
42 if (sparseContainer.count(_key) == 1)
43 {
44 return;
45 }
46
47 // valueの値を格納.
48 denseContainer.push_back(_value);
49
50 //格納する引数を計算
51 unsigned int index = denseContainer.size() - 1;
52
53 // 疎な配列を登録.
54 sparseContainer.emplace(_key, index);
55
56 // 反転も登録
57 indexToKey.push_back(_key);
58 }
59
60 /// <summary>
61 /// _key要素を削除する
62 /// </summary>
63 /// <param name="_key">削除する要素のKey</param>
64 void Erase(const Key& _key)
65 {
66
67 // Keyが存在しない場合返す
68 if (sparseContainer.count(_key) == 0)
69 {
70 return;
71 }
72
73
74 //引数を記憶
75 unsigned int index = sparseContainer[_key];
76 //末尾要素の引数を記憶
77 unsigned int lastIndex = denseContainer.size() - 1;
78
79 //自身が末尾の場合 or 自身のみしか格納してない場合.
80 // 末尾の場合交換せずに処理できる
81
82 //自身が末尾要素でない場合、awapを行う
83 if (index != lastIndex)
84 {
85 //最後の要素と入れ替える
86 std::swap(denseContainer[index], denseContainer[lastIndex]);
87
88 //疎配列の交換
89 sparseContainer[indexToKey[lastIndex]] = index;
90
91 //indexToKeyの交換
92 std::swap(indexToKey[index], indexToKey[lastIndex]);
93 }
94
95 //各配列の削除処理を行う.
96 {
97 //要素の削除
98 denseContainer.pop_back();
99 //疎配列の削除
100 sparseContainer.erase(_key);
101 //Keyの逆引きを削除
102 indexToKey.pop_back();
103 }
104 }
105
106
107 operator std::vector<Value>& ()
108 {
109 return denseContainer;
110 }
111
112 Value& operator[](Key _key)
113 {
114 return denseContainer[sparseContainer[_key]];
115 }
116 };
117}
Definition SparseSet.hpp:16
std::vector< Key > indexToKey
denseをループ処理するときにkeyがほしい時などに使うやつ
Definition SparseSet.hpp:31
void Add(const Key &_key, const Value &_value)
配列の追加
Definition SparseSet.hpp:39
std::unordered_map< Key, unsigned int > sparseContainer
疎な配列、keyを引数としてvalue配列の引数を取得する
Definition SparseSet.hpp:21
Value & operator[](Key _key)
Definition SparseSet.hpp:112
void Erase(const Key &_key)
_key要素を削除する
Definition SparseSet.hpp:64
std::vector< Value > denseContainer
密な配列、実際のバリューが格納される
Definition SparseSet.hpp:26
Definition Accessor.hpp:110