[英]More elegant boost accumulation in C++11?
boost文档将此作为如何使用boost::accumulate
的示例:
// The data for which we wish to calculate statistical properties:
std::vector< double > data( /* stuff */ );
// The accumulator set which will calculate the properties for us:
accumulator_set< double, features< tag::tail<left> > > acc(
tag::tail<left>::cache_size = 4 );
// Use std::for_each to accumulate the statistical properties:
std::for_each( data.begin(), data.end(), bind<void>( ref(acc), _1 ) );
有没有更优雅的方法在C ++ 11/14中使用基于范围的循环或lambdas编写此代码?
我能想到两种方法,如下:
std::vector< double > data = {2.1, 2.2, 3.3, 4.4, 5.5};
accumulator_set< double, features< tag::tail<left> > > acc(tag::tail<left>::cache_size = 4);
for_each(data.begin(), data.end(), [&acc](double y){ acc(y); });
要么
std::vector< double > data = {2.1, 2.2, 3.3, 4.4, 5.5};
accumulator_set< double, features< tag::tail<left> > > acc(tag::tail<left>::cache_size = 4);
for (auto y : data)
acc(y);
std::vector<double> data = {2.1, 2.2, 3.3, 4.4, 5.5};
std::set<double> least;
for (auto&& x:data) {
least.insert(decltype(x)(x));
if (least.size() > 4)
least.erase( std::prev(least.end()) );
}
在字符方面,基本相同的大小。 因为它使用了众所周知的std
原语,所以更容易阅读和理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.