Solidity

無法將數字添加到 Solidity 上的數組

  • May 21, 2018

我有一個接收數字的函式,autentic評估它是否已經在一個數組中,如果它應該返回 false,如果不是,則返回 true。然後onlyOneVote如果為真,則將數字添加到數組中,如果為假,則不添加。問題是該函式從不向數組添加任何內容。

uint32[100] public people;
uint8 public counter;

function onlyOneVote(uint32 ida) public returns(bool) {
 bool a = autentic(ida);
 if (a == true) {
   people[counter] = ida;
   counter = counter + 1;
 }
 return a;
}

function autentic(uint32 idb) public returns(bool) {
 bool b;
 for(uint i = 0; i< people.length; i++) {
   if (people[i] == idb) {
     b = false;
     break;
   } else {
     b = true;
   }
 }
 return b;
} 

我認為可以肯定地說您的程式碼可以簡化為:

uint32[100] public people;
uint8 public counter;

mapping (uint32 => bool) public alreadyVoted;

function vote(uint32 id) public returns(bool) {
 if (alreadyVoted[id]) return(false);
 alreadyVoted[id] = true;
 people[counter] = id;
 counter = counter + 1;
 return(true);
}

像這樣用 web3 呼叫它:

contractInstance.vote.sendTransaction(id, {from: _from});

您的帳戶地址在哪裡_from(web3.eth.accounts

$$ 0 $$也許)。

這段程式碼可以做到,它已經過測試,在這裡你有在 Kovan 上與之互動的地址:0xc807caebda01eaffd7998ab7fd9fcc4a2cf5730c

pragma solidity ^0.4.18; 


contract Test {

uint32[100] public people;
uint256 public counter; // Is uint256 because the on the array[100], 100 is a uint256 variable.
mapping(uint32 => bool) public voteVerifier; //mapping saves you so much gas at checking if it's in the array


function onlyOneVote(uint32 ida) public returns(bool) {
 require(!voteVerifier[ida]); //If false, enter to add the uint32 to array.

   people[counter] = ida; //Add the ida to the array
   counter = counter + 1;

   voteVerifier[ida] = true;//Set on the mapping that this uint32 is now on the array.
 return true;
}

}

有幾點要評論:

  • 使用映射來檢查數組中是否存在數字要好得多,因為它不是時間相關的搜尋。Find params on arrays使您在數組變得更大時進行更多操作。但是使用映射,即使數組中包含數百萬個值,搜尋也會持續並且成本相同

在這裡你有一些資訊:http ://solidity.readthedocs.io/en/v0.4.21/types.html#mappings

這段程式碼:people[counter] = ida; //Add the ida to the array counter = counter + 1;

可以更換為更準確和更便宜的天然氣支出:people.push(ida)//Puts on the last array's position the item ida;

希望能幫助到你!!

引用自:https://ethereum.stackexchange.com/questions/48852