我很喜欢用C++ 11,并试图想出一个更优雅的方式来对两个std::vector<double>
进行两两比较。对于成对最大,我使用的是相当不雅使用C++ 11 std :: vector元素进行两两比较lambda表达式
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;
}
但是,使用lambda表达式和std::for_each
似乎更好,因为其中提取std::vector<double>
的绝对最大下面,但我不来了什么。
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;
};
伊戈尔的文章后,我现在有:
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); });
两个问题:
- 为什么不直接复制到
vec a
像vec c
我以前? - 是不是使用back_inserter添加了很多额外的操作?如果从
c==a
开始,那么将需要更少的插入到c
。
像这样:
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;
伊戈尔的方法更高效那么你原来的方法。如果a和b包含均匀分布的随机值,那么您的原始方法将创建1.5 N个副本,但Igor的方法仅创建1 N个副本。 – atb