Java HashSet equivalent in C++

后端 未结 1 1893
星月不相逢
星月不相逢 2021-02-19 00:33

I was curious if there was something akin the Java HashSet in C++? I.e. a data structure with a fast look, as I will only be running .contains(e) on it. Likewise, i

相关标签:
1条回答
  • 2021-02-19 01:04

    You can use std::unordered_set<> (standard § 23.5.6), its find method (to do a lookup) as an average complexity of O(1) :

    #include <iostream>
    #include <unordered_set>
    
    int main()
    {  
        std::unordered_set<int> example = {1, 2, 3, 4};
    
        auto search = example.find(2);
        if(search != example.end()) {
            std::cout << "Found " << (*search) << '\n';
        }
        else {
            std::cout << "Not found\n";
        }
    }
    

    EDIT:

    As suggested by @Drew Dormann, you can alternatively use count, which also has a average complexity of O(1):

    #include <iostream>
    #include <unordered_set>
    
    int main()
    {  
        std::unordered_set<int> example = {1, 2, 3, 4};
    
        if(example.count(2)) {
            std::cout << "Found\n";
        }
        else {
            std::cout << "Not found\n";
        }
    }
    
    0 讨论(0)
提交回复
热议问题