remove element from dyn array by element, (not by index)

Bjoern nanali at nospam-wanadoo.fr
Tue Jan 15 02:04:03 PST 2008


Hi,
unlike the examples I found on D.learn regarding this topic I want to 
remove an element from an dynamic array without knowing the index.

A few questions :

//Remove element try #1
T[] remove(T,E)(T[] arr, E element)
{
   for(uint i = 0;i < arr.length-1;i++)
   {
     if (arr[i] == element)
       return i==arr.length-1 ? arr[0..$-1].dup : arr[0..i] ~ arr[i+1 
.. $];		
   }
   // return T[]    ???????????????????
}

or is it preferable to use :
//Remove element try #2
void remove(T,E)(inout T[] arr, in E element)
{}

Given :
class myclass
{
   this(int x){}
}

myclass[] objarr;

auto a = new myclass(1);
objarr ~= a;
auto b = new myclass(2);
objarr ~= b;
auto c = new myclass(3);
objarr ~= c;

objarr.remove(b);

Do I need opEquals within myclass ?

Let's assume that the passed parameter is f.i. a priority index. In case 
  that I want to sort objarr ordered by this /priority index/, is 
toHash() the override of choice ?

Can you please help me to improve the code ?
Many thanks in advance, Bjoern


More information about the Digitalmars-d-learn mailing list