【问题标题】:How to find duplicate entry in Solidity array如何在数组中查找重复项
【发布时间】:2022-01-01 16:53:11
【问题描述】:

我正在编写一个函数,它应该接收一个 uint 数组,并且我想要求数组中的所有元素都不相同 并且 中的所有元素数组是属于数组的预选元素的一部分。到目前为止,我有:

    function vote(uint[] memory proposals) external
    {
        Voter storage sender = voters[msg.sender];
        require(sender.weight != 0, "Has no right to vote.");
        require(!sender.voted, "Already voted.");
        mapping(uint => bool) duplicateVotes;
        require(!duplicateVotes, "Cannot vote for a proposal more than once.");
        sender.voted = true;
        sender.vote = proposals;

        proposals[proposals].voteCount += sender.weight;
    }

但我得到一个错误:

The data location must be "storage", "memory" or "calldata" for variable, but none was given.

但我认为这个错误只是一个更大问题的症状。谁能帮我找出解决这个问题的办法?

【问题讨论】:

    标签: arrays blockchain ethereum solidity smartcontracts


    【解决方案1】:

    我认为你想实现同一个人不会投票两次,但你这样做的方式计算成本很高,这会花费太多的 gas。相反,如果选民之前投票过,请创建一个映射来跟踪:

     mapping(address=>bool) peopleWhoVoted;
    

    你还想保留选民数组

     address[] public listOfVoters;
    

    所以在你的投票函数中,确保这个函数-msg.sender 的调用者不在peopleWhoVoted 映射中

        function vote(pass argument) public {
           // msg.sender is globally available, it is function caller
           require(!peopleWhoVoted[msg.sender],"this caller already voted")
           // now u are sure that this caller did not vote before
           // so u can add the function caller to the array
           listOfVoters.push(msg.sender)
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-16
      • 2014-01-26
      相关资源
      最近更新 更多