# Solidity 遍历mapping

Solidity 专栏收录该内容
3 篇文章 0 订阅

## insert 方法

function insert(itmap storage self, uint key, uint value) returns (bool replaced)
{
uint keyIndex = self.data[key].keyIndex;
self.data[key].value = value;
if (keyIndex > 0)
return true;
else
{
keyIndex = self.keys.length++;
self.data[key].keyIndex = keyIndex + 1;
self.keys[keyIndex].key = key;
self.size++;
return false;
}
}

## remove方法

function remove(itmap storage self, uint key) returns (bool success)
{
uint keyIndex = self.data[key].keyIndex;
if (keyIndex == 0)
return false;
delete self.data[key];
self.keys[keyIndex - 1].deleted = true;
self.size --;
}

## iterate_next方法

function iterate_next(itmap storage self, uint keyIndex) returns (uint r_keyIndex)
{
keyIndex++;
while (keyIndex < self.keys.length && self.keys[keyIndex].deleted)
keyIndex++;
return keyIndex;
}

## iterate_get方法

function iterate_get(itmap storage self, uint keyIndex) returns (uint key, uint value)
{
key = self.keys[keyIndex].key;
value = self.data[key].value;
}

pragma solidity ^0.4.7;
import {IterableMapping} from 'https://github.com/ethereum/dapp-bin/library/iterable_mapping.sol';

contract MappingsIterable {
using IterableMapping for IterableMapping.itmap;
IterableMapping.itmap public data;

function insertValue(uint _key, uint _value) public {
data.insert(_key, _value);
}
// 计算mapping中所有value的和
function sum() returns (uint s)
{
for (uint i = IterableMapping.iterate_start(data); IterableMapping.iterate_valid(data, i); i = IterableMapping.iterate_next(data, i))
{
(uint key, uint value) = IterableMapping.iterate_get(data, i);
s += value;
}
}
}
• 1
点赞
• 0
评论
• 1
收藏
• 一键三连
• 扫一扫，分享海报

08-26
10-29 4747
02-21 1万+
10-08 3763
07-24 620
03-31 409
08-08 276
04-01 933
11-11 726
12-18 484
10-27 2万+
12-27 7802
11-09 207
02-22 1万+