Algorithm remove Tid

monarch_dodra monarchdodra at gmail.com
Wed Jan 22 08:03:46 PST 2014


On Wednesday, 22 January 2014 at 15:41:58 UTC, bearophile wrote:
> monarch_dodra:
>
>> Maybe you confusing the new style lambda for a "greater equal" 
>> operator? I can't make sense of your question any other way.
>
> My point was that the shown code doesn't remove only one item 
> in presence of duplicated ones. In this case tid are unique, 
> but in general using that code to remove one item is not a good 
> idea.
>
> Bye,
> bearophile

Ah... I see. Yeah, this will remove *all* items that match the 
TID. I'm not sure that's a problem in this context, but I you did 
want to remove "at most" 1 item, then this isn't the correct 
solution.

There's no phobos solution for that, but I guess it would be 
written something like:

template removeOne(alias pred, SwapStrategy s = 
SwapStrategy.stable)
{
     Range removeOne(Range)(Range range)
     {
         auto result = range.save;
         auto f = find!pred(range);
         if (f.empty) return result;

         static if (s == SwapStrategy.stable)
         {
             auto ff = f.save;
             f.popFront();
             ff.popBack;
             for ( ; !f.empty; f.popFront(), ff.popFront())
                 moveFront(f, ff);
         }
         else
         {
             move(find.back, find.front);
         }
         result.popBack();
         return result;
     }
}

Disclaimer: Not actually tested. May also horribly fail on 
non-reference ranges.


More information about the Digitalmars-d-learn mailing list