Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashSet equivalent in C++

Tags:

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.

like image 489
user1352683 Avatar asked Jul 09 '14 01:07

user1352683


People also ask

Does C++ have HashSet?

Definition of C++ hashset. Hashset can be defined as an unordered collection that consists of unique elements. Hashset consists of standard operation collection such as Contains, Remove, Add; it also constitutes of the standard set-based operations like symmetric difference, intersection, and union.

What is a HashSet C#?

In C#, HashSet is an unordered collection of unique elements. This collection is introduced in . NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.

What is a Java HashSet?

HashSet is a class that extends AbstractSet and implements the Set interface in Java. It is a very useful tool that allows you to store unique items and access them in constant time (on average). No duplicate values are stored.

Is Set same as HashSet?

A Set is a generic set of values with no duplicate elements. A TreeSet is a set where the elements are sorted. A HashSet is a set where the elements are not sorted or ordered.


1 Answers

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";
    }
}
like image 63
quantdev Avatar answered Oct 10 '22 23:10

quantdev