Std set in solidity?

by chatzich   Last Updated April 14, 2019 22:28 PM

Is there any way or library to have a set in solidity that can be iterated like C++'s std::set?

    library Set {
  // We define a new struct datatype that will be used to
  // hold its data in the calling contract.
  struct Data { mapping(string => bool) flags; }

  // Note that the first parameter is of type "storage
  // reference" and thus only its storage address and not
  // its contents is passed as part of the call.  This is a
  // special feature of library functions.  It is idiomatic
  // to call the first parameter `self`, if the function can
  // be seen as a method of that object.
  function insert(Data storage self, string memory value)
      public
      returns (bool)
  {
      if (self.flags[value])
          return false; // already there
      self.flags[value] = true;
      return true;
  }

  function remove(Data storage self, string memory value)
      public
      returns (bool)
  {
      if (!self.flags[value])
          return false; // not there
      self.flags[value] = false;
      return true;
  }

  function contains(Data storage self, string memory value)
      public
      view
      returns (bool)
  {
      return self.flags[value];
  }
}

This is an implementation I found but this struct can not be iterated

Tags : solidity


Answers 1


The closest thing you can have is using a mapping and an array, a bit like you did.

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;
        }
    }
}
Eli Drion
Eli Drion
April 14, 2019 21:11 PM

Related Questions


Updated October 09, 2018 12:28 PM

Updated November 28, 2018 04:28 AM

Updated December 12, 2018 08:28 AM

Updated January 10, 2019 23:28 PM

Updated July 23, 2018 00:28 AM