Consider two vectors:
vector<int> A = {1, 4, 3};
vector<int> B = {5, 7, 1};
It's given both vectors are of equal length.
If I need to use element by element at each index and perform an operation, say counting number of indices with absolute difference less than or equal to a given value 3
.
Ideally, a for loop based implementation looks like this:
int cnt{0};
for(int i{0}; i < 3; i++)
if(abs(A[i] - B[i]) <= 3)
cnt++;
}
However, I'm tempted to use a standard function like std::mismatch
to perform the same.
int cnt{ 0 };
auto count_close_ones = [&](int const &a, int const &b) {
if (abs(a - b) <= 3)
cnt++;
return true;
};
std::mismatch(A.begin(), A.end(), B.begin(), count_close_ones);
Is it recommended? On one hand, I'm using a standard library function, so less prone to errors. On the other hand, the name mismatch
may be misleading.
This question is not specific to std::mistmatch
, it's just an example. I use std::adjacent_find
too in the same way to iterate over pair of elements in same vector instead of two for loops.
Is it generally advisable?