vendredi 28 mai 2021

algorithm in STL to sweep 2 ranges and call a function

Is there a algorithm in STL that will sweep two (equally sized) ranges and call a function for each pair of entries?

std::equal() and std::transform() seem to follow this notion, but they are not that expressive when the intention is to, say, calculate the sum of difference squares of two vectors:

vector<double> a = { 1.1, 1.0, 5.5 };
vector<double> b = { 1.4, 1.1, 5.3 };

// intended action
double sum_of_squared_diffs ( vector<double> a, vector<double> b ) {

   double sum =0;
   for (size_t i=0; i<a.size(); i++) {    // a.size() == b.size()
       sum += std::pow(a[i] - b[i], 2.0);
   }
   return sum;
}

// expressed with std::equal :(
double sum = 0;
std::equal(a.begin(), a.end(), 
           b.begin(), b.end(), [&sum](double a, double b) {
   sum += std::pow(a-b, 2.0);
   return false;
});
  • is there a more suitable algorithm in STL to express the intention?
  • should I write my own?
  • or are there better ways of writing this, preferably for C++11/14 ?

Aucun commentaire:

Enregistrer un commentaire