[Ethereum] Could mapping data structure return the number of items it points

contract-designcontract-developmentmappingsolidity

For example following code piece from https://ethereum.stackexchange.com/a/10763/4575 . I have added new lines that is followed by //*.

pragma solidity ^0.4.2;
contract test {    
  struct my_struct {
    int a;
    int my_length; //*to keep track of the length.
  }

  mapping (address=>my_struct[]) Map;

  function fill_map(my_struct struct1,my_struct struct2) internal  {    
    Map[msg.sender].push(struct1);
    Map[msg.sender][0].my_length = Map[msg.sender][0].my_length + 1;//*

    Map[msg.sender].push(struct2);   
    Map[msg.sender][0].my_length = Map[msg.sender][0].my_length + 1;//*

    Map[msg.sender].push(struct3);//*  
    Map[msg.sender][0].my_length = Map[msg.sender][0].my_length + 1;//*

    delete Map[id][2]; //*struct3 will be removed.
    Map[msg.sender][0].my_length = Map[msg.sender][0].my_length - 1;//*
  }
}

I can obtain data as follows: Map[id][index].a; index is an integer number. In this example it can be 0 (for struct1) or 1 (for struct2).

As we know Java could return the number of object inside a list:

String[] array = new String[10];
int size = array.length;

Is there anything similar as: Map[id].length ? or manually after each push or delete should I need to keep length?

On my solution Map[msg.sender][0].my_length will return the number of the pointed structs from Map[msg.sender].

Best Answer

there is some mistakes (or i didn't understand well your question) in your previous code and i think also in your question.

in your case you have a map of arrays. so Map[key].length exists and return the size of the corresponding array to your key. so Map[msg.sender].length is correct but Map[msg.sender][0].length is not. because in this second case you are returning the first struct which doesn't have a length parameter but a my_length.

Related Topic