Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet data structure in Solidity

Is there any way of implementing a set in Solidity, in order to check if an element exists, in O(1) average? I have been thinking of using a mapping object with no values, is that faster than using an array and iterating in order to find elements?

like image 816
Marcel Avatar asked Sep 02 '25 16:09

Marcel


1 Answers

Yes in sense of speed you are better off using a mapping. The closest thing to a set in solidity is to us a mapping and an array. But it will have terrible cost to iterate when you want to remove an element.

Mapping Example

mapping (address => bool) yourMapping; // maps address (key) to boolean (value)

Set Example

contract Contract {

    struct Set {
        uint[] values;
        mapping (uint => bool) is_in;
    }

    Set my_set;

    function add(uint a) public {
         if (!my_set.is_in[a]) {
             my_set.values.push(a);
             my_set.is_in[a] = true;
         }
    }
}
like image 161
Mitch Avatar answered Sep 05 '25 14:09

Mitch