jeudi 31 mars 2016

Compare all elements of a std::vector with every other element in the same vector efficiently

I'm new to C++.

I'm trying to find how to iterate through a vector to compare every element with every other element, where the comparison order is irrelevant where;

(a 'compared to' b) = (b 'compared to' a)

So checking one means you don't need to compare every value to EVERY other value, just the remaining ones.

I have something that's like this TOY algorithm;

#include <vector>

typedef std::vector<double> vector_t;

int countTheFoo(const vector_t &v)
{
  int fooFound {0};
  for (auto it1 = v.begin(); (it1 != v.end()); it1++)
  {
    for (auto it2 = it1.next(); (it2 != v.end()); it2++)
    {
      if testForFoo(*it1, *it2)
      {
        // Woot! Found some...
        fooFound++;
      }
    }
  }
  return fooFound;
}

vector_t foo { 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0 };

int numFoo {countTheFoo(foo)};

I'm actually comparing lines to find ones which intersect not simple doubles but the technique would be the same.

It's the;

for (auto it2 = it1.next(); (it2 != v.end()); it2++)

part that I think could be done more efficiently using lambdas.

This approach works, but;

  • Is it the most efficient way of doing this sort of iteration?

  • Can it be done as a lambda using std::for_all()?

Thank you.

Aucun commentaire:

Enregistrer un commentaire