vendredi 2 avril 2021

Iterate over all the other objects excluding the current one

In many applications is necessary to compute the mutual interactions between a sequence of objects, that is for each object of the sequence, iterate over all the other objects except/skipping/excluding the current one. That's my current solution to this:

std::vector<Object> objects;
for( auto icurr=objects.begin(); icurr!=objects.end(); ++icurr )
   {// Iterate over all the other objects excluding this one
    for( auto iother=objects.begin(); iother!=icurr; ++iother )
        icurr->interact_with(*iother);
    for( auto iother=icurr+1; iother!=objects.end(); ++iother )
        icurr->interact_with(*iother);
   }

But this doesn't satisfy me because it's cumbersome and above all duplicates the loop body. I don't like the banal alternative either:

for( auto icurr=objects.begin(); icurr!=objects.end(); ++icurr )
   {
    for( auto iother=objects.begin(); iother!=objects.end(); ++iother )
        if(icurr!=iother) icurr->interact_with(*iother);
   }

Because has an avoidable test; in that case, I would rather write something like:

for( Object& curr : objects )
   {
    for( const Object& other : objects.excluded(curr) )
        curr.interact_with(other);
   }

But I have no idea how. There's a better solution here using the latest c++ standard? Any advice?

Aucun commentaire:

Enregistrer un commentaire