I'm kind of having fun with C++11 and trying to come up with a more elegant way of taking a pairwise comparison of two std::vector<double>
. For pairwise maximum, I am using the rather inelegant
typedef std::vector<double> vec;
vec pairwiseMax(vec& a, vec& b)
{
ASSERT(a.size() == b.size());
vec c(a); // seed with a
for (unsigned int i = 0; i < a.size(); i++)
{
if (b[i] > a[i]) // bigger than
c[i] = b[i];
}
return c;
}
However, using lambdas and std::for_each
would seem better, as in the following which extracts the absolute maximum of a std::vector<double>
but I'm not coming up with anything.
inline double vecabs(vec v)
{
if (v.empty()) return 0.0;
vec::iterator it =
std::max_element(v.begin(), v.end(),
// Start lambda function
[](double const& a, double const& b)
{
return (std::abs(a) < std::abs(b));
});
return *it;
};
After Igor's post, I now have:
vec c;
c.reserve(a.size());
std::transform(a.begin(), a.end(), b.begin(),
std::back_inserter(c),
[](double const& d, double const& e)
{ return max(d, e); });
Two questions:
- Why not just copy
vec a
intovec c
like I had before? - Isn't using the back_inserter adding a lot of additional operations? If
c==a
to start with, then fewer inserts toc
would be required.
Like this:
vec c(a); // seed with a
std::transform(a.begin(), a.end(), b.begin(),
c.begin(),
[](double const& d, double const& e)
{ return max(d, e); });
return c;