21

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, if you could enlighten me on how to do a .contains() on whatever data structure you propose, I would be very appreciative. O, please do not post just look at the c++ docs as I have already done so and found them burdensome.

Milan
  • 1,743
  • 2
  • 13
  • 36
user1352683
  • 397
  • 1
  • 3
  • 14

1 Answers1

20

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";
    }
}
quantdev
  • 23,517
  • 5
  • 55
  • 88
  • 4
    I'd recommend `count()` for emulating contains(). That 2 line if becomes simply `if(example.count(2))` โ€“ Drew Dormann Jul 09 '14 at 01:57
  • 4
    The function was named `count()` to be consistent with multisets, but for `unordered_set` it will only return `1 (true)` or `0 (false)` โ€“ Drew Dormann Jul 09 '14 at 02:09