[LeetCodeブラシノート]C++unordered_set常用操作

5440 ワード

[1]では一般的なSTLコンテナの概要を述べたが,筆者はブラシ問題の過程でSTLコンテナの関数をいくつか調べる必要があることが多く不便であるため,ここではSTLコンテナでよく用いられる操作についてメモする.std::unordered_setは、STLが提供する無秩序な集合のクラスであり、集合の特徴は、あるデータに重複するデータがあるかどうかを記録し、選択するのに非常に適している重複する要素がないことである.std::unordered_setstd::setが異なる点は、前者は順序がなく、後者は要素の順序を並べ替えることであり、順序がないからこそ、無秩序setの速度がずっと速いことである.通常、挿入と削除は定数時間で行えます.無秩序setのキー値はその内容値と同じで、mapとは異なり、その内容を変更することはできませんが、要素を挿入したり削除したりすることができます.
クラス宣言のプロトタイプは次のとおりです.
template < class Key,                        // unordered_set::key_type/value_type
           class Hash = hash<Key>,           // unordered_set::hasher
           class Pred = equal_to<Key>,       // unordered_set::key_equal
           class Alloc = allocator<Key>      // unordered_set::allocator_type
           > class unordered_set;

その中で最も注意しなければならないのはkeyのデータ型の指定です.一般的な関数も多くありません.
  • find()検索要素
  • insert()挿入要素
  • erase()削除要素
  • clear()クリア容器
  • empty()容器が空かどうかを判断する
  • .
  • size()返却容器の大きさ
  • 無秩序setの使用方法を以下の例で学びます.
    #include 
    using namespace std;
    
    int main() {
    	unordered_set<int> s = {1,2,3,4};
    	auto got = s.find(2);
    	if (got == s.end()) 
    		cout << "not found" << endl ;
    	else
    		cout << "element" << *got << " is found" << endl;
    	
    	s.insert(5);
    	s.erase(5);
    	s.clear(); //     
    }
    

    Reference
    [1]. https://blog.csdn.net/LoseInVain/article/details/104189784