Solidity 中的 HashSet 数据结构

Mar*_*cel 4 ethereum solidity

有没有什么方法可以在 Solidity 中实现一个集合,以便检查一个元素是否存在,平均时间为 O(1) ?我一直在考虑使用没有值的映射对象,这比使用数组并迭代来查找元素更快吗?

thi*_*tch 5

是的,从速度的角度来看,您最好使用映射。对我们来说,最接近集合的东西是映射和数组。但是当你想删除一个元素时,迭代的成本会很高。

映射示例

mapping (address => bool) yourMapping; // maps address (key) to boolean (value)
Run Code Online (Sandbox Code Playgroud)

树立榜样

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;
         }
    }
}
Run Code Online (Sandbox Code Playgroud)