競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
HashSet<Key,Hasher,KeyEqual>は、重複しないキーを所有する順序なし集合です。
以下、size_typeはstd::size_t、Nは登録数、Cは現在の容量、C′は再配置後の容量です。ハッシュ・比較・値操作の費用は別途加わります。
HashSet() = default;
explicit HashSet(size_type expected, Hasher hash = {}, KeyEqual equal = {});
HashSet(std::initializer_list<Key> keys, Hasher hash = {}, KeyEqual equal = {});
template <std::input_iterator It, std::sentinel_for<It> Sentinel> HashSet(It first, Sentinel last, Hasher hash = {}, KeyEqual equal = {});
HashSet(const HashSet&) = default;
HashSet(HashSet&& other);
空集合を作成できます。予約容量、初期値リスト、iteratorで表した範囲を指定して構築することもできます。コピーは独立です。
制約: 冒頭の値型・演算の前提を満たすこと。指定する列長は内部容量の上限内です。
計算量: 空の構築はO(1)。予約・範囲構築の費用はreserveとinsert_rangeに準じます。 ムーブ構築はO(1)、コピーは保持領域に比例。
insertiterator insert(const Key& key);
iterator insert(Key&& key);
追加した要素または登録済みの同じキーを指すiteratorを返します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 期待償却O(1)。再配置や衝突集中時の上界は共通の計算量を参照。
insert_checkedstd::pair<iterator, bool> insert_checked(const Key& key);
std::pair<iterator, bool> insert_checked(Key&& key);
キーが未登録なら追加し、{iterator,追加したか}を返します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 期待償却O(1)。再配置や衝突集中時の上界は共通の計算量を参照。
emplacetemplate <class... Args> std::pair<iterator, bool> emplace(Args&&... args);
argsからキーを構築し、{iterator,追加したか}を返します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 期待償却O(1)。再配置や衝突集中時の上界は共通の計算量を参照。
insert_rangetemplate <std::input_iterator It, std::sentinel_for<It> Sentinel> void insert_range(It first, Sentinel last);
範囲内のキーを追加します。重複は増やしません。
制約: 有効な範囲を渡し、同じ表のiteratorを入力にしないこと。
計算量: M個の追加に期待償却O(M)、再配置の費用は共通の計算量に従います。
finditerator find(const Key& key) const;
指定キーのiteratorを返します。不在ならend()です。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 期待O(1)、最悪O(C)。ハッシュ・比較・値のコピー費用は別です。
containbool contain(const Key& key) const;
指定したキーが登録されていればtrueを返します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 期待O(1)、最悪O(C)。ハッシュ・比較・値のコピー費用は別です。
containsbool contains(const Key& key) const;
指定したキーが登録されていればtrueを返します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 期待O(1)、最悪O(C)。ハッシュ・比較・値のコピー費用は別です。
countint count(const Key& key) const;
登録済みなら1、不在なら0を返します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 期待O(1)、最悪O(C)。ハッシュ・比較・値のコピー費用は別です。
eraseiterator erase(const_iterator it, bool get_next = true);
iterator erase(const Key& key, bool get_next = true);
指定キーに対応する要素、またはiteratorが指す要素を削除し、次のiteratorを返します。get_next=falseならend()です。キーが見つからない場合やiteratorがend()の場合は何も変更しません。
制約: iterator版は同じ表の有効なiteratorまたはend()を渡すこと。
計算量: 次iteratorを探す形は最悪O(C)。false指定はキー版が期待償却O(1)、iterator版がO(1)。
erase_iftemplate <class Predicate> size_type erase_if(Predicate predicate);
述語を満たす要素を削除し、削除数を返します。
制約: 述語から同じ表を変更しないこと。
計算量: O(C)、空表はO(1)。述語の費用は別です。
beginiterator begin() const noexcept;
friend iterator begin(const HashSet& set) noexcept;
先頭のiteratorを返します。列挙順は規定しません。
制約: 共通の所有・iteratorの有効期間に従います。
計算量: 最悪O(C)、空表はO(1)。全走査はO(C)。
enditerator end() const noexcept;
friend iterator end(const HashSet& set) noexcept;
終端iteratorを返します。
制約: 共通の所有・iteratorの有効期間に従います。
計算量: O(1)。
cbeginconst_iterator cbegin() const noexcept;
先頭のconst_iteratorを返します。
制約: 共通の所有・iteratorの有効期間に従います。
計算量: 最悪O(C)、空表はO(1)。全走査はO(C)。
cendconst_iterator cend() const noexcept;
終端const_iteratorを返します。
制約: 共通の所有・iteratorの有効期間に従います。
計算量: O(1)。
sizesize_type size() const noexcept;
要素数を返します。
制約: 共通の前提を満たすこと。
計算量: O(1)。
emptybool empty() const noexcept;
空ならtrueを返します。
制約: 共通の前提を満たすこと。
計算量: O(1)。
capacitysize_type capacity() const noexcept;
確保済みのバケット数を返します。
制約: 共通の前提を満たすこと。
計算量: O(1)。
load_factordouble load_factor() const noexcept;
登録数を容量で割った使用率を返します。
制約: 共通の前提を満たすこと。
計算量: O(1)。
reservevoid reserve(size_type count);
指定した要素数まで再確保せず格納できる容量を予約します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 再配置時は期待O(C+C′)、最悪O(C+C′+N²)。予約済みreserveはO(1)。
rehashvoid rehash(size_type requested);
指定数以上のバケットへ再配置します。
制約: 共通のキー・ハッシュ・同値判定の前提を満たすこと。
計算量: 再配置時は期待O(C+C′)、最悪O(C+C′+N²)。予約済みreserveはO(1)。
clearvoid clear() noexcept;
容量を保って全要素と墓石を削除します。
制約: 共通の前提を満たすこと。
計算量: O(C)。要素・墓石がなければO(1)。
swapvoid swap(HashSet& other);
friend void swap(HashSet& left, HashSet& right) noexcept;
内容と設定を交換します。
制約: 共通の前提を満たすこと。
計算量: O(1)。値型・比較器のswapの費用は別です。
operator==friend bool operator==(const HashSet& left, const HashSet& right);
格納するキー集合が等しければtrueを返します。
制約: 共通の所有・iteratorの有効期間に従います。
計算量: 期待O(両表の容量)。空同士はO(1)、衝突集中で増加します。
bool operator!=(const HashSet& left, const HashSet& right);
C++23のoperator==から得られる不等値比較です。
格納するキー集合が異なればtrueを返します。
制約: 共通の所有・iteratorの有効期間に従います。
計算量: 期待O(両表の容量)。空同士はO(1)、衝突集中で増加します。
C/C’は再配置前後の容量、Nは登録数です。ハッシュ・比較・要素操作をO(1)として記します。列キーのハッシュは列長に比例します。衝突集中時の再配置は最悪O(C+C’+N²)。予約済みreserveはO(1)、削除では自動縮小せずrehash(0)で縮めます。
次のiteratorを返すeraseは最悪O(C)です。falseを指定すると、キー指定の削除は期待償却O(1)、有効なiteratorでの削除はO(1)です。erase_ifの述語から表を変更してはいけません。
HashSet<int> values;
values.insert(7);
assert(values.contains(7));
values.erase(7, false);
assert(values.empty());
Keyはコピー可能、またはムーブ構築がnoexceptであることが必要です。コピーはKeyのコピー構築を使って独立し、ムーブ元は空。キーの書き換えは禁止です。再配置・clear・swap・ムーブでiteratorと参照が無効になり、eraseは対象だけを無効にします。
Hasher/KeyEqualは同値なキーへ同じハッシュを返し、登録中に規則を変えません。swapは両比較器の非送出swapが前提です。借用キーの参照先は登録中に寿命・内容を保ち、削除後は解放できます。同じ要素の集合は種・列挙順によらず同じ外側ハッシュになりますが、独自の同値関係には対応する外側Hasherも必要です。
同梱GenericHash()は実行時の種、GenericHash(seed)は指定種で構築し、operator()(x)は整数・列挙・浮動値・tuple・range・std::hash対応型を再帰的にハッシュ化します。unorderedコンテナの列挙順は無視します。
SKIP_RUNTIME_CHECKSでiterator検査を除きます。検査有効でも全ての無効な再利用を検出する保証はありません。容量保護は維持し、追加SIMDはSIRKIT_DISABLE_SIMDで除外できます。
operator=HashSet& operator=(HashSet other);
コピーまたはムーブで内容を置き換え、自身への参照を返します。コピーは独立した内容を持ちます。
制約: 型・所有・例外保証は共通の説明に従います。
計算量: 保持する配列・ノードのコピーと旧内容の破棄に比例。ムーブ構築とは異なり、代入では旧内容の解放費用も含みます。
GenericHash();
explicit constexpr GenericHash(std::uint64_t seed) noexcept;
省略形は実行時の種、引数形は指定した種で構築します。同じ個体の規則は一定です。
制約: 同値なキーには同じハッシュ値を返すこと。独自の同値関係には対応するHasherを用意します。
計算量: O(1)。
GenericHash::operator()template<class T> std::uint64_t operator()(const T& value) const;
整数・列挙・浮動小数・tuple・range・std::hash対応型を再帰的にハッシュ化します。unorderedコンテナの要素順は無視します。
制約: 構成要素もハッシュ化可能であること。std::hash対応型の結果はその実装にも依存します。
計算量: 固定幅の整数はO(1)、tupleは各要素の和、列は走査する要素数とそのハッシュ費用の和。
[HashSet<Key,Hasher,KeyEqual>]
Flat table。検索・追加・次iteratorを求めない削除は期待償却O(1)。列キーのハッシュ計算は列長に比例する。
次iteratorへの移動は空き区間長に比例する。削除では自動縮小しないため、疎になればrehash(0)で縮小する。
再配置・clear・swap・ムーブでiterator/参照は無効。eraseは対象だけを無効にする。
Keyはコピー可能、またはムーブ構築がnoexceptであること。
Hasher/KeyEqualは同値なキーに同じハッシュ値を返し、格納中に規則を変えないこと。
iterator/参照の無効化後の使用は禁止。検査でも全ての使い回しは検出しない。
HashSet()/HashSet(n, hash, equal): 空集合を作り、後者はn要素分を予約する。
HashSet({keys}, hash, equal)/HashSet(first,last,hash,equal): 指定したキー列から構築する。
insert(const Key&)/insert(Key&&): コピー/ムーブで追加しiteratorを返す。重複時は既存要素を返す。
insert_checked(const Key&)/insert_checked(Key&&): コピー/ムーブで追加し、{iterator, 追加の有無}を返す。
emplace(args...): Keyを構築して追加し、{iterator, 追加の有無}を返す。
insert_range(first,last): 入力iteratorの範囲を追加する。同じ表のiteratorは渡さないこと。
find(key): 対応するiteratorを返す。未登録はend()。キーの変更は禁止する。
contain(key)/contains(key)/count(key): 登録済みか、または登録数0/1を返す。
erase(it, next=true): 削除して次のiteratorを返す。falseならO(1)でend()。erase(end())もend()。
erase(key, next=true): キーを削除して次のiteratorを返す。falseなら期待O(1)でend()。未登録もend()。
erase_if(pred): pred(const Key&)がtrueの要素を削除し、削除数を返す。空ならO(1)、他はO(capacity())。predは表を変更しないこと。
begin()/end()/cbegin()/cend(): 順序不定で列挙する。逆向き移動もでき、キーはconst参照。
空集合のbeginはO(1)、それ以外は先頭要素までのバケットを走査する。
size()/empty()/capacity()/load_factor(): 要素数・空か・バケット数・使用率をO(1)で返す。
clear(): O(capacity())で全要素を破棄し、確保済み容量を再利用する。
reserve(n): n要素分を予約し縮小しない。予約済みはO(1)、再配置は期待O(C+C')。
rehash(n): nバケット以上・登録数に足りる容量へ再配置し墓石を除く。期待O(C+C')。
C/C'=旧/新バケット数、N=登録数。衝突による再配置の最悪時間はO(C+C'+N^2)。
ハッシュ・同値判定・要素操作をO(1)とする。全列挙はO(C)、空集合はO(1)。
HashSet(other)/operator=(other): 独立したコピーを作る。コピーにはKeyのコピー構築が必要。
HashSet(move(other))/operator=(move(other)): 内容を移動し、移動元は空で再利用可能。
swap(other): 内容とハッシュ・同値判定を交換する。O(1)。
operator==(other)/!=: 要素数と両方向のcontainsで比較する。期待O(両表の容量)。
swapはHasher/KeyEqualのswapが例外を送出しないことを要求する。
[GenericHash]
GenericHash(): 実行時に選んだ種で構築する。同じオブジェクトでは結果は一定。
GenericHash(seed): 指定した種で構築する。std::hash対応型の結果はその実装にも依存する。
operator()(x): 整数・列挙・浮動小数・tuple・range・std::hash対応型を再帰的にハッシュ化する。
unorderedコンテナの要素順は無視する。独自の同値関係には対応するHasherも用意する。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| 文字列検索(HashSet<string>) | coverage_hash_set_string_search.cpp | 未提出 | — |
| ABC344 C - A+B+C | hash_set_membership.cpp | 参考検証・移行先あり | AC |
| ABC164 C - gacha | hash_set_strings.cpp | 現行未照合・要再提出 | AC |
| ABC073 C - Write and Erase | hash_set_toggle.cpp | 参考検証・移行先あり | AC |
| HashSet local independent checks | hash_set_unit.cpp | ローカル補足 | — |
| AND Set (HashSet) | preferred_data_hash_set_and_yuki.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0 AND LicenseRef-SplitMix64-Public-Domain
// SplitMix64部分(GenericHash::mix)はCC0ではなく、原著者のPD提供声明・無条件許諾に従う。
// CC0-1.0はそれ以外の部分に適用する。SplitMix64の提供条件:
// https://github.com/reinsirk/sirkit-cpp-library/blob/main/LICENSES/LicenseRef-SplitMix64-Public-Domain.txt
// Original Source(GenericHash::mixのみ。Sebastiano Vigna、PD提供声明・無条件許諾):
// https://prng.di.unimi.it/splitmix64.c
// 参考: https://nyaannyaan.github.io/library/hashmap/hashset.hpp
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/hash_set.md
//
// API一覧
// [HashSet<Key,Hasher,KeyEqual>]
// Flat table。検索・追加・次iteratorを求めない削除は期待償却O(1)。列キーのハッシュ計算は列長に比例する。
// 次iteratorへの移動は空き区間長に比例する。削除では自動縮小しないため、疎になればrehash(0)で縮小する。
// 再配置・clear・swap・ムーブでiterator/参照は無効。eraseは対象だけを無効にする。
// Keyはコピー可能、またはムーブ構築がnoexceptであること。
// Hasher/KeyEqualは同値なキーに同じハッシュ値を返し、格納中に規則を変えないこと。
// iterator/参照の無効化後の使用は禁止。検査でも全ての使い回しは検出しない。
// HashSet()/HashSet(n, hash, equal): 空集合を作り、後者はn要素分を予約する。
// HashSet({keys}, hash, equal)/HashSet(first,last,hash,equal): 指定したキー列から構築する。
// insert(const Key&)/insert(Key&&): コピー/ムーブで追加しiteratorを返す。重複時は既存要素を返す。
// insert_checked(const Key&)/insert_checked(Key&&): コピー/ムーブで追加し、{iterator, 追加の有無}を返す。
// emplace(args...): Keyを構築して追加し、{iterator, 追加の有無}を返す。
// insert_range(first,last): 入力iteratorの範囲を追加する。同じ表のiteratorは渡さないこと。
// find(key): 対応するiteratorを返す。未登録はend()。キーの変更は禁止する。
// contain(key)/contains(key)/count(key): 登録済みか、または登録数0/1を返す。
// erase(it, next=true): 削除して次のiteratorを返す。falseならO(1)でend()。erase(end())もend()。
// erase(key, next=true): キーを削除して次のiteratorを返す。falseなら期待O(1)でend()。未登録もend()。
// erase_if(pred): pred(const Key&)がtrueの要素を削除し、削除数を返す。空ならO(1)、他はO(capacity())。predは表を変更しないこと。
// begin()/end()/cbegin()/cend(): 順序不定で列挙する。逆向き移動もでき、キーはconst参照。
// 空集合のbeginはO(1)、それ以外は先頭要素までのバケットを走査する。
// size()/empty()/capacity()/load_factor(): 要素数・空か・バケット数・使用率をO(1)で返す。
// clear(): O(capacity())で全要素を破棄し、確保済み容量を再利用する。
// reserve(n): n要素分を予約し縮小しない。予約済みはO(1)、再配置は期待O(C+C')。
// rehash(n): nバケット以上・登録数に足りる容量へ再配置し墓石を除く。期待O(C+C')。
// C/C'=旧/新バケット数、N=登録数。衝突による再配置の最悪時間はO(C+C'+N^2)。
// ハッシュ・同値判定・要素操作をO(1)とする。全列挙はO(C)、空集合はO(1)。
// HashSet(other)/operator=(other): 独立したコピーを作る。コピーにはKeyのコピー構築が必要。
// HashSet(move(other))/operator=(move(other)): 内容を移動し、移動元は空で再利用可能。
// swap(other): 内容とハッシュ・同値判定を交換する。O(1)。
// operator==(other)/!=: 要素数と両方向のcontainsで比較する。期待O(両表の容量)。
// swapはHasher/KeyEqualのswapが例外を送出しないことを要求する。
//
// [GenericHash]
// GenericHash(): 実行時に選んだ種で構築する。同じオブジェクトでは結果は一定。
// GenericHash(seed): 指定した種で構築する。std::hash対応型の結果はその実装にも依存する。
// operator()(x): 整数・列挙・浮動小数・tuple・range・std::hash対応型を再帰的にハッシュ化する。
// unorderedコンテナの要素順は無視する。独自の同値関係には対応するHasherも用意する。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <bit>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <memory>
#include <optional>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
#include <emmintrin.h>
#endif
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_GENERIC_HASH_DEFINED
#define SIRKIT_GENERIC_HASH_DEFINED
struct GenericHash {
private:
std::uint64_t seed_;
static constexpr std::uint64_t mix(std::uint64_t x) noexcept {
x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);
x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb);
return x ^ (x >> 31);
}
template <class> static constexpr bool dependent_false = false;
template <class T> static constexpr bool integral_pair = requires (const T& value) {
value.first; value.second;
requires std::is_integral_v<std::remove_cvref_t<decltype(value.first)>>;
requires std::is_integral_v<std::remove_cvref_t<decltype(value.second)>>;
};
template <class T>
std::uint64_t raw(const T& value) const {
using U = std::remove_cvref_t<T>;
if constexpr (std::is_integral_v<U>) {
static_assert(sizeof(U) <= sizeof(std::uint64_t), "GenericHash: integer exceeds 64 bits");
return static_cast<std::uint64_t>(value);
} else if constexpr (std::is_enum_v<U>) {
return static_cast<std::uint64_t>(static_cast<std::underlying_type_t<U>>(value));
} else if constexpr (requires { typename std::tuple_size<U>::type; }) {
std::uint64_t result = seed_;
std::apply([&](const auto&... elements) {
((result = result * UINT64_C(11995408973635179863) + raw(elements)), ...);
}, value);
return mix(result ^ std::tuple_size_v<U>);
} else if constexpr (requires { typename U::hasher; typename U::key_equal; std::begin(value); std::end(value); }) {
// 同じ要素集合は列挙順にかかわらず同じ値になる。
std::uint64_t sum = 0, second = 0, count = 0;
for (const auto& element : value) {
const auto h = mix(raw(element) + seed_);
sum += h;
second += h * h;
++count;
}
return mix(sum ^ std::rotl(second, 23) ^ count);
} else if constexpr (requires { { std::hash<U>{}(value) } -> std::convertible_to<std::size_t>; }) {
// 浮動小数の+0/-0もstd::hashに従い等しい値にする。
return static_cast<std::uint64_t>(std::hash<U>{}(value));
} else if constexpr (requires { std::begin(value); std::end(value); }) {
std::uint64_t result = seed_, count = 0;
for (const auto& element : value) {
result = result * UINT64_C(11995408973635179863) + raw(element);
++count;
}
return mix(result ^ count);
} else {
static_assert(dependent_false<U>, "GenericHash: provide std::hash or a custom Hasher for this key");
}
}
public:
GenericHash() : GenericHash(static_cast<std::uint64_t>(
std::chrono::steady_clock::now().time_since_epoch().count())) {}
explicit constexpr GenericHash(std::uint64_t seed) noexcept : seed_(mix(seed) | 1) {}
template <class T>
std::uint64_t operator()(const T& value) const noexcept(
std::is_integral_v<T> || std::is_enum_v<T> || integral_pair<T>) {
using U = std::remove_cvref_t<T>;
if constexpr (std::is_integral_v<U> || std::is_enum_v<U>) {
return (raw(value) ^ seed_) * UINT64_C(11995408973635179863);
} else if constexpr (integral_pair<U>) {
return (raw(value.first) ^ seed_) * UINT64_C(11995408973635179863) +
(raw(value.second) ^ seed_) * UINT64_C(10150724397891781847);
} else return raw(value) * seed_;
}
};
#endif
#ifndef SIRKIT_HASH_CAPACITY_DEFINED
#define SIRKIT_HASH_CAPACITY_DEFINED
namespace detail {
inline void CheckHashCapacity(std::size_t requested, std::size_t maximum, const char* message) {
if (requested > maximum) throw std::length_error(message);
}
}
#endif
#ifndef SIRKIT_HASH_SET_DEFINED
#define SIRKIT_HASH_SET_DEFINED
template <class Key, class Hasher = GenericHash, class KeyEqual = std::equal_to<Key>>
class HashSet {
public:
using key_type = Key;
using value_type = Key;
using Data = value_type;
using size_type = std::size_t;
private:
friend GenericHash;
using hasher = Hasher;
using key_equal = KeyEqual;
// 自明にコピーできる型はunionに格納し、空きスロットの構築とoptionalの状態領域を省く。
// 構築に失敗しうる型はoptionalで未構築状態を管理する。
union CompactSlot {
std::remove_cv_t<value_type> value;
// 新しいスロットでは値を構築しない。unionの暗黙copy/moveはオブジェクト表現をコピーする。
CompactSlot() noexcept {}
value_type& operator*() noexcept { return value; }
const value_type& operator*() const noexcept { return value; }
value_type* operator->() noexcept { return std::addressof(value); }
const value_type* operator->() const noexcept { return std::addressof(value); }
template <class... Args> void emplace(Args&&... args) {
value_type next(std::forward<Args>(args)...);
std::construct_at(std::addressof(value), std::move(next));
}
void reset() noexcept {} // 自明な破棄なので、削除状態だけをstate_で変更する。
};
using Slot = std::conditional_t<
std::is_nothrow_default_constructible_v<value_type> &&
std::is_nothrow_move_constructible_v<value_type> &&
std::is_trivially_copy_constructible_v<value_type> &&
std::is_trivially_destructible_v<value_type>, CompactSlot, std::optional<value_type>>;
static_assert(std::is_copy_constructible_v<value_type> ||
std::is_nothrow_move_constructible_v<value_type>,
"HashSet: entries must be copyable or nothrow movable");
static_assert(std::is_copy_constructible_v<Hasher> && std::is_copy_constructible_v<KeyEqual> &&
std::is_nothrow_swappable_v<Hasher> && std::is_nothrow_swappable_v<KeyEqual>,
"HashSet: Hasher and KeyEqual must be copyable and nothrow swappable");
std::vector<Slot> slots_;
std::vector<std::uint8_t> state_; // 0=空、1=登録済み、2=削除済み
size_type size_ = 0, occupied_ = 0;
unsigned shift_ = 64;
[[no_unique_address]] Hasher hash_;
[[no_unique_address]] KeyEqual equal_;
#ifndef SKIP_RUNTIME_CHECKS
size_type generation_ = 0;
#endif
void invalidate() noexcept {
#ifndef SKIP_RUNTIME_CHECKS
++generation_;
#endif
}
size_type max_capacity() const noexcept {
return std::bit_floor(std::min(slots_.max_size(), state_.max_size()));
}
static size_type threshold(size_type capacity) noexcept { return capacity == 0 ? 0 : (capacity - 1) / 2; }
size_type bucket(const Key& key, unsigned shift) const noexcept(
std::is_nothrow_invocable_v<const Hasher&, const Key&>) {
const auto h = static_cast<std::uint64_t>(hash_(key));
if constexpr (std::is_same_v<Hasher, GenericHash>) return static_cast<size_type>(h >> shift);
else return static_cast<size_type>((h * UINT64_C(11995408973635179863)) >> shift);
}
size_type locate(const Key& key) const {
if (size_ == 0) return slots_.size();
size_type p = bucket(key, shift_);
while (state_[p]) {
if (state_[p] == 1 && equal_(*slots_[p], key)) return p;
p = (p + 1) & (slots_.size() - 1);
}
return slots_.size();
}
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
// 登録状態を16スロットずつ判定し、有効なキーだけを移す。
void rebuild_simd(size_type capacity) {
std::vector<Slot> next(capacity);
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
// 値の構築前に領域を一定間隔で準備する。
if constexpr (std::is_same_v<Slot, CompactSlot>) {
if (capacity >= 256) {
constexpr size_type stride = std::max(size_type{1}, size_type{4096} / sizeof(Slot));
for (size_type i = 0; i < capacity; i += stride)
*reinterpret_cast<volatile unsigned char*>(std::addressof(next[i])) = 0;
}
}
#endif
std::vector<std::uint8_t> state(capacity, 0);
const auto shift = static_cast<unsigned>(64 - std::countr_zero(capacity));
const auto live = _mm_set1_epi8(1);
for (size_type base = 0; base < slots_.size(); base += 16) {
const auto states = _mm_loadu_si128(reinterpret_cast<const __m128i*>(state_.data() + base));
unsigned mask = static_cast<unsigned>(_mm_movemask_epi8(_mm_cmpeq_epi8(states, live)));
while (mask) {
const size_type i = base + std::countr_zero(mask);
size_type p = bucket(*slots_[i], shift);
while (state[p]) p = (p + 1) & (capacity - 1);
next[p].emplace(*slots_[i]);
state[p] = 1;
mask &= mask - 1;
}
}
slots_.swap(next); state_.swap(state);
occupied_ = size_; shift_ = shift; invalidate();
}
#endif
void rebuild(size_type capacity) {
detail::CheckHashCapacity(capacity, max_capacity(), "HashSet: capacity overflow");
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
if constexpr (std::is_same_v<Slot, CompactSlot>) {
if (slots_.size() >= 64) { rebuild_simd(capacity); return; }
}
#endif
std::vector<Slot> next(capacity);
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
// 値の構築前に領域を一定間隔で準備する。
if constexpr (std::is_same_v<Slot, CompactSlot>) {
if (capacity >= 256) {
constexpr size_type stride = std::max(size_type{1}, size_type{4096} / sizeof(Slot));
for (size_type i = 0; i < capacity; i += stride)
*reinterpret_cast<volatile unsigned char*>(std::addressof(next[i])) = 0;
}
}
#endif
std::vector<std::uint8_t> state(capacity, 0);
const auto shift = static_cast<unsigned>(64 - std::countr_zero(capacity));
if constexpr (std::is_nothrow_move_constructible_v<value_type> &&
std::is_nothrow_invocable_v<const Hasher&, const Key&>) {
for (size_type i = 0; i < slots_.size(); ++i) {
if (state_[i] != 1) continue;
size_type p = bucket(*slots_[i], shift);
while (state[p]) p = (p + 1) & (capacity - 1);
next[p].emplace(std::move(*slots_[i]));
state[p] = 1;
}
} else {
// 例外を送出しうるハッシュは、移動を始める前に全移動先を計算する。
std::vector<std::pair<size_type, size_type>> positions;
positions.reserve(size_);
for (size_type i = 0; i < slots_.size(); ++i) {
if (state_[i] != 1) continue;
size_type p = bucket(*slots_[i], shift);
while (state[p]) p = (p + 1) & (capacity - 1);
state[p] = 1;
positions.emplace_back(i, p);
}
for (const auto& [old, dest] : positions) {
if constexpr (std::is_nothrow_move_constructible_v<value_type>)
next[dest].emplace(std::move(*slots_[old]));
else next[dest].emplace(*slots_[old]);
}
}
slots_.swap(next);
state_.swap(state);
occupied_ = size_;
shift_ = shift;
invalidate();
}
size_type insertion_slot(const Key& key) {
if (slots_.empty()) rebuild(8);
for (;;) {
size_type p = bucket(key, shift_);
// 削除前は墓石の分岐と探索位置の記録を省く。
if (occupied_ == size_) {
while (state_[p]) {
if (equal_(*slots_[p], key)) return p;
p = (p + 1) & (slots_.size() - 1);
}
if (size_ != threshold(slots_.size())) return p;
detail::CheckHashCapacity(slots_.size(), max_capacity() / 2, "HashSet: capacity overflow");
rebuild(slots_.size() * 2);
continue;
}
size_type first_deleted = slots_.size();
while (state_[p]) {
if constexpr (std::is_same_v<Slot, CompactSlot> && std::is_integral_v<Key> &&
(std::is_same_v<KeyEqual, std::equal_to<Key>> ||
std::is_same_v<KeyEqual, std::equal_to<void>>)) {
// 外部参照のない整数と標準比較だけ、同値キーの墓石で止める。
if (equal_(*slots_[p], key)) return p;
} else if (state_[p] == 1 && equal_(*slots_[p], key)) return p;
if (state_[p] == 2 && first_deleted == slots_.size()) first_deleted = p;
p = (p + 1) & (slots_.size() - 1);
}
if (first_deleted != slots_.size()) return first_deleted;
if (occupied_ != threshold(slots_.size())) return p;
rebuild(slots_.size());
}
}
void mark_inserted(size_type p) noexcept {
if (state_[p] == 0) ++occupied_;
state_[p] = 1;
++size_;
}
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
size_type next_live(size_type p) const noexcept {
const auto capacity = state_.size();
if (capacity - p >= 4) {
if (state_[p] == 1) return p;
if (state_[p+1] == 1) return p+1;
if (state_[p+2] == 1) return p+2;
if (state_[p+3] == 1) return p+3;
p += 4;
}
const auto live = _mm_set1_epi8(1);
while (capacity - p >= 16) {
const auto states = _mm_loadu_si128(reinterpret_cast<const __m128i*>(state_.data()+p));
const unsigned mask = static_cast<unsigned>(_mm_movemask_epi8(_mm_cmpeq_epi8(states,live)));
if (mask) return p + std::countr_zero(mask);
p += 16;
}
while (p < capacity && state_[p] != 1) ++p;
return p;
}
size_type previous_live(size_type p) const noexcept {
if (p >= 4) {
if (state_[p-1] == 1) return p-1;
if (state_[p-2] == 1) return p-2;
if (state_[p-3] == 1) return p-3;
if (state_[p-4] == 1) return p-4;
p -= 4;
}
const auto live = _mm_set1_epi8(1);
while (p >= 16) {
const auto states = _mm_loadu_si128(reinterpret_cast<const __m128i*>(state_.data()+p-16));
const unsigned mask = static_cast<unsigned>(_mm_movemask_epi8(_mm_cmpeq_epi8(states,live)));
if (mask) return p - 16 + std::bit_width(mask) - 1;
p -= 16;
}
while (p != 0) { --p; if (state_[p] == 1) return p; }
return state_.size();
}
#endif
public:
class Iterator {
friend class HashSet;
const HashSet* owner_ = nullptr;
size_type index_ = 0;
#ifndef SKIP_RUNTIME_CHECKS
size_type generation_ = 0;
#endif
Iterator(const HashSet* owner, size_type index) noexcept : owner_(owner), index_(index) {
#ifndef SKIP_RUNTIME_CHECKS
generation_ = owner->generation_;
#endif
}
void check(bool element) const {
#ifndef SKIP_RUNTIME_CHECKS
if (!owner_ || generation_ != owner_->generation_ || index_ > owner_->slots_.size() ||
(element && index_ == owner_->slots_.size()) ||
(index_ < owner_->slots_.size() && owner_->state_[index_] != 1))
throw std::out_of_range("HashSet: invalid iterator");
#else
(void)element;
#endif
}
public:
using iterator_category = std::bidirectional_iterator_tag;
using iterator_concept = std::bidirectional_iterator_tag;
using value_type = Key;
using difference_type = std::ptrdiff_t;
using reference = const Key&;
using pointer = const Key*;
Iterator() noexcept = default;
reference operator*() const { check(true); return *owner_->slots_[index_]; }
pointer operator->() const { return std::addressof(operator*()); }
Iterator& operator++() {
check(true);
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
if constexpr (!std::is_same_v<Slot, CompactSlot>) {
index_ = owner_->next_live(index_ + 1);
return *this;
}
#endif
do { ++index_; } while (index_ < owner_->slots_.size() && owner_->state_[index_] != 1);
return *this;
}
Iterator operator++(int) { auto copy = *this; ++*this; return copy; }
Iterator& operator--() {
check(false);
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
if constexpr (!std::is_same_v<Slot, CompactSlot>) {
const auto p = owner_->previous_live(index_);
if (p != owner_->slots_.size()) { index_ = p; return *this; }
#ifndef SKIP_RUNTIME_CHECKS
throw std::out_of_range("HashSet: iterator before begin");
#else
index_ = 0;
return *this;
#endif
}
#endif
auto p = index_;
while (p != 0) { --p; if (owner_->state_[p] == 1) { index_ = p; return *this; } }
#ifndef SKIP_RUNTIME_CHECKS
throw std::out_of_range("HashSet: iterator before begin");
#else
index_ = 0;
return *this;
#endif
}
Iterator operator--(int) { auto copy = *this; --*this; return copy; }
bool operator==(const Iterator& other) const noexcept {
return owner_ == other.owner_ && index_ == other.index_;
}
};
using iterator = Iterator;
using const_iterator = Iterator;
using itr = iterator;
HashSet() = default;
explicit HashSet(size_type expected, Hasher hash = {}, KeyEqual equal = {})
: hash_(std::move(hash)), equal_(std::move(equal)) { reserve(expected); }
HashSet(std::initializer_list<Key> keys, Hasher hash = {}, KeyEqual equal = {})
: HashSet(keys.size(), std::move(hash), std::move(equal)) { insert_range(keys.begin(), keys.end()); }
template <std::input_iterator It, std::sentinel_for<It> Sentinel>
HashSet(It first, Sentinel last, Hasher hash = {}, KeyEqual equal = {})
: hash_(std::move(hash)), equal_(std::move(equal)) { insert_range(first, last); }
HashSet(const HashSet&) = default;
HashSet(HashSet&& other) noexcept(std::is_nothrow_copy_constructible_v<Hasher> &&
std::is_nothrow_copy_constructible_v<KeyEqual> &&
std::is_nothrow_swappable_v<Hasher> &&
std::is_nothrow_swappable_v<KeyEqual>)
: hash_(other.hash_), equal_(other.equal_) { swap(other); }
HashSet& operator=(HashSet other) { swap(other); return *this; }
void swap(HashSet& other) noexcept(std::is_nothrow_swappable_v<Hasher> && std::is_nothrow_swappable_v<KeyEqual>) {
static_assert(std::is_nothrow_swappable_v<Hasher> && std::is_nothrow_swappable_v<KeyEqual>,
"HashSet: Hasher and KeyEqual must be nothrow swappable");
using std::swap;
swap(hash_, other.hash_); swap(equal_, other.equal_);
slots_.swap(other.slots_); state_.swap(other.state_);
swap(size_, other.size_); swap(occupied_, other.occupied_); swap(shift_, other.shift_);
invalidate(); other.invalidate();
}
iterator begin() const noexcept {
if (size_ == 0) return end();
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
if constexpr (!std::is_same_v<Slot, CompactSlot>) return iterator(this,next_live(0));
#endif
size_type p = 0; while (state_[p] != 1) ++p;
return iterator(this, p);
}
iterator end() const noexcept { return iterator(this, slots_.size()); }
const_iterator cbegin() const noexcept { return begin(); }
const_iterator cend() const noexcept { return end(); }
friend iterator begin(const HashSet& set) noexcept { return set.begin(); }
friend iterator end(const HashSet& set) noexcept { return set.end(); }
iterator find(const Key& key) const { return iterator(this, locate(key)); }
bool contains(const Key& key) const { return locate(key) != slots_.size(); }
bool contain(const Key& key) const { return contains(key); }
int count(const Key& key) const { return contains(key) ? 1 : 0; }
size_type size() const noexcept { return size_; }
bool empty() const noexcept { return size_ == 0; }
size_type capacity() const noexcept { return slots_.size(); }
double load_factor() const noexcept { return slots_.empty() ? 0.0 : static_cast<double>(size_) / slots_.size(); }
private:
template <class K>
std::pair<iterator, bool> insert_checked_impl(K&& key) {
const auto p = insertion_slot(key);
if (state_[p] == 1) return {iterator(this, p), false};
slots_[p].emplace(std::forward<K>(key));
mark_inserted(p);
return {iterator(this, p), true};
}
public:
std::pair<iterator, bool> insert_checked(const Key& key) { return insert_checked_impl(key); }
std::pair<iterator, bool> insert_checked(Key&& key) { return insert_checked_impl(std::move(key)); }
iterator insert(const Key& key) { return insert_checked(key).first; }
iterator insert(Key&& key) { return insert_checked(std::move(key)).first; }
template <class... Args>
std::pair<iterator, bool> emplace(Args&&... args) {
Key key(std::forward<Args>(args)...);
return insert_checked(std::move(key));
}
template <std::input_iterator It, std::sentinel_for<It> Sentinel>
void insert_range(It first, Sentinel last) {
for (; first != last; ++first) insert(*first);
}
iterator erase(const_iterator it, bool get_next = true) {
#ifndef SKIP_RUNTIME_CHECKS
if (it.owner_ != this || it.generation_ != generation_) throw std::out_of_range("HashSet::erase: foreign or stale iterator");
#endif
if (it.index_ == slots_.size()) return end();
it.check(true);
const auto p = it.index_;
slots_[p].reset(); state_[p] = 2; --size_;
if (!get_next) return end();
#if !defined(SIRKIT_DISABLE_SIMD) && defined(__SSE2__) && (defined(__x86_64__) || defined(__i386__)) && defined(__GNUC__) && !defined(__clang__)
if constexpr (!std::is_same_v<Slot, CompactSlot>) return iterator(this,next_live(p+1));
#endif
auto next = iterator(this, p);
do { ++next.index_; } while (next.index_ < slots_.size() && state_[next.index_] != 1);
return next;
}
iterator erase(const Key& key, bool get_next = true) { return erase(find(key), get_next); }
template <class Predicate>
size_type erase_if(Predicate predicate) {
if (size_ == 0) return 0;
size_type removed = 0;
for (size_type i = 0; i < slots_.size(); ++i) {
if (state_[i] == 1 && std::invoke(predicate, std::as_const(*slots_[i]))) {
slots_[i].reset(); state_[i] = 2; --size_; ++removed;
}
}
return removed;
}
friend void swap(HashSet& left, HashSet& right) noexcept { left.swap(right); }
friend bool operator==(const HashSet& left, const HashSet& right) {
if (left.size_ != right.size_) return false;
if (left.size_ == 0) return true;
for (const auto& key : left) if (!right.contains(key)) return false;
for (const auto& key : right) if (!left.contains(key)) return false;
return true;
}
void clear() noexcept {
if (occupied_ == 0) { invalidate(); return; }
for (size_type i = 0; i < slots_.size(); ++i) if (state_[i] == 1) slots_[i].reset();
std::fill(state_.begin(), state_.end(), std::uint8_t{0});
size_ = occupied_ = 0; invalidate();
}
void reserve(size_type count) {
if (count <= threshold(slots_.size())) return;
if (count > threshold(max_capacity())) throw std::length_error("HashSet::reserve: capacity overflow");
size_type capacity = 8;
while (count > threshold(capacity)) capacity *= 2;
rebuild(capacity);
}
void rehash(size_type requested) {
if (requested > max_capacity()) throw std::length_error("HashSet::rehash: capacity overflow");
size_type capacity = 8;
while (requested > capacity || size_ > threshold(capacity)) capacity *= 2;
rebuild(capacity);
}
};
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1