美文网首页
c++ 使用unordered_set实现hashset

c++ 使用unordered_set实现hashset

作者: TFprime | 来源:发表于2019-03-05 19:12 被阅读0次

    使用unordered_set库来构造hashset

    unordered_set 官方文档介绍

    Unordered sets are containers that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value.
    In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely. Keys are immutable, therefore, the elements in an unordered_set cannot be modified once in the container - they can be inserted and removed, though.
    Internally, the elements in the unordered_set are not sorted in any particular order, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their values (with a constant average time complexity on average).
    unordered_set containers are faster than set containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.
    Iterators in the container are at least forward iterators.
    简单来说,unordered_key非常的高效,使用值本身作为键值

    Example

    #include<iostream>
    #include<unordered_set>
    using namespace std;
    
    int main() {
        // 1. initialize a hash set
        unordered_set<int> hashset;
        // 2. insert a new key
        hashset.insert(1);
        hashset.insert(2);
        hashset.insert(3);
        // 3. delete a key
        hashset.erase(2);
        // 4. check if the key is in the hash set
        if (hashset.count(2) <= 0) {
            cout << "Key 2 is not in the hash set." << endl;
        }
        // 5. get the size of the hash set
        cout << "The size of the hash set is " << hashset.size() << endl;
        // 6. iterate the hash set
        for (auto it = hashset.begin(); it != hashset.end(); it++) {
            cout << (*it) << " ";
        }
        cout << "is in the hash set." << endl;
        // 7. clear the hash set
        hashset.clear();
        // 8. check if the hash set is empty
        if (hashset.empty()) {
            cout << "hash set is empty now!" << endl;
        }
        
        return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:c++ 使用unordered_set实现hashset

          本文链接:https://www.haomeiwen.com/subject/ougouqtx.html