Created
February 13, 2022 08:21
-
-
Save DraperDanMan/5ef17e2a141b7a2113fe253283495fb7 to your computer and use it in GitHub Desktop.
Simple AF SparseSet in C++17
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include "SparseSet.h" | |
| void SparseSet::insert(int64_t value) | |
| { | |
| ASSERT(!contains(value)); | |
| m_dense_array[m_dense_head] = value; | |
| m_sparse_array[value] = m_dense_head; | |
| m_dense_head++; | |
| } | |
| void SparseSet::remove(int64_t value) | |
| { | |
| ASSERT(contains(value)); | |
| int64_t dense_idx = m_sparse_array[value]; | |
| int64_t last_idx = m_dense_head-1; | |
| if (dense_idx == last_idx) | |
| { | |
| m_dense_head--; | |
| return; | |
| } | |
| int64_t last_value = m_dense_array[last_idx]; | |
| m_dense_array[dense_idx] = last_value; | |
| m_sparse_array[last_value] = dense_idx; | |
| m_dense_head--; | |
| } | |
| bool SparseSet::contains(int64_t value) | |
| { | |
| int64_t dense_idx = m_sparse_array[value]; | |
| return dense_idx < m_dense_head && m_dense_array[dense_idx] == value; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include <vector> | |
| #include "Assert.h" | |
| struct SparseSet | |
| { | |
| SparseSet(int64_t capacity) : m_dense_head(0), m_dense_array(capacity), m_sparse_array(capacity) {} | |
| void insert(int64_t value); | |
| void remove(int64_t value); | |
| bool contains(int64_t value); | |
| inline void clear() { m_dense_head = 0; } | |
| std::vector<int64_t>::iterator dense_begin() { return m_dense_array.begin();} | |
| std::vector<int64_t>::iterator sparse_begin() { return m_sparse_array.begin();} | |
| std::vector<int64_t>::iterator dense_end() { return m_dense_array.end();} | |
| std::vector<int64_t>::iterator sparse_end() { return m_sparse_array.end();} | |
| private: | |
| int m_dense_head; | |
| std::vector<int64_t> m_dense_array; | |
| std::vector<int64_t> m_sparse_array; | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Was just mucking around. 👍