[Ethereum] How to loop through mapping in solidity

mappingsolidity

I have a mapping in my contract like below:

mapping (address => uint) public voterCount;

To calculate the total votes, I would like to loop through the mapping and sum the uint values. How do I do this in solidity? One solution is to use another variable say totalVotes that is incremented every time voterCount is updated. I am trying to see if there is a cleaner solution where I don't need an additional variable to keep track of the count.

Best Answer

You can't loop through the keys or count the keys in a mapping (but patterns exist for accomplishing such functionality using a few more variables).

You're on the right path, tracking it yourself. For example:

pragma solidity ^0.4.8;

contract Vote {

  uint public totalVotes;

  mapping (address => uint) public voterCount;

  function vote(uint votes) returns(bool success) {
    totalVotes += votes;
    voterCount[msg.sender] += votes; // cumulative
    return true;
  }
}

You wouldn't want to iterate over the voters in the contract in any case because that would put an upper bound on the number of voters before the system stops working - due to rising transaction cost hitting the block gas limit.

I can show you how to make the voter list iterable but it's not obvious that it's really needed to count the votes as we go. Keeping it simple for first answer.

Hope it helps.

Related Topic