Aller au contenu

Photo

Peer review of array functions


  • Veuillez vous connecter pour répondre
3 réponses à ce sujet

#1
georage

georage
  • Members
  • 247 messages
Thanks to Phaenan for writing the first one, but I am hoping if some gurus will look these over and suggest improvements to the other two.

I have tested the first two (index and add) but not delete. Seems like it should work though.

My question on the delete function is how will having an empty entry in the array affect things? Will GetArraySize still return a valid value if you had an array with 10 names in it put deleted the first 2? 

Hopefully others find these useful.

[nwscript]
///////////////////////////array functions///////////////////////
int GetStringArrayIndex(string [] sHaystack, string sNeedle)
{
int iSize=GetArraySize(sHaystack);
if(iSize==0) return -1;
int iIndex;
for ( iIndex = 0; iIndex < iSize; iIndex++ )    
{    
if(sHaystack[iIndex]==sNeedle)return iIndex;    
}
return -1;
}

////////////////////
void AddStringToArray(string [] sArray, string sAdd)
{
int iPosition=GetArraySize(sArray);  
if(GetStringArrayIndex(sArray,sAdd)==-1) //only add unique entries    
sArray[iPosition]=sAdd;
}

////////////////////
void DeleteStringFromArray(string [] sArray, string sDelete)
{
int iDelete=GetStringArrayIndex(sArray,sDelete);
if(iDelete>=0)//only delete if it exists in array     
sArray[iDelete]="";
}
[/nwscript]

Modifié par georage, 12 décembre 2009 - 01:14 .


#2
georage

georage
  • Members
  • 247 messages
These forums stink for posting code! I edited the above and it should reformat soon.

#3
FalloutBoy

FalloutBoy
  • Members
  • 580 messages
They look like they will do what you want, however...



Depending on the under-the-hood implementation, string comparisons will range somewhere between horribly slow to kind of slow. If I were you, I would just make it a point to never add duplicate strings and remove that check in the add function. Otherwise you are going to loop and compare every element of the array each time you add something which could be a lot of compares.




#4
georage

georage
  • Members
  • 247 messages
Cool, thanks for the tip! I will do that.