Logo

Programming-Idioms

  • Go
  • C++
  • Fortran

Idiom #34 Create a set of objects

Declare and initialize a set x containing unique objects of type T.

class T:
    def __init__(self, x):
        self.x = x
    def __hash__(self):
        return hash(self.x)
    def __eq__(self, t):
        return self.x == t.x
x = {T('abc'), T(123), T(lambda: ...)}
class T(object):
    pass

x = set(T())
class T:
   ...

s = set(T() for _ in range(x))

`...` is a placeholder, `pass` can also be used
x := make(map[T]struct{})

The struct{} type is space efficient because it occupies zero bytes in memory.
x := make(map[T]bool)

There is no built-in Set type, but you can create a Map with key type T and boolean value (which will be ignored).
#include <unordered_set>
std::unordered_set<T, hasher, eq> x;

Using a custom hasher and eq (equality checking function)
#include <unordered_set>
std::unordered_set<T> x;

T must be hashable
using System.Collections.Generic;
HashSet<T> x = new HashSet<T>();

Where T is the type of element

New implementation...