And*_*yUK 2 c++ functor simplify
我有一个基本上从双向量中读取值的函数,将它们附加到一个字符串(同时确保每个字符串之间的空间并设置它们的精度)并返回最终结果,减去最后的空格:
std::string MultiplePrintProperties::GetHpitchString()
{
std::string str;
vector< double >::iterator it;
for ( it = Vals.begin();
it != Vals.end();
it++ )
{
ostringstream s;
// Set precision to 3 digits after the decimal point
// and read into the string
boost::format fmt( "%.3f " );
s << fmt % *( it );
str.append( s.str() );
}
// Remove last white space and return string
return str.substr( 0, str.length() - 1 );
}
Run Code Online (Sandbox Code Playgroud)
我想知道这段代码是否可以以任何方式简化.我最近一直在调查for_each和functor的使用,但是我们无法弄清楚这些技术如何改进这个特定的例子.
xto*_*ofl 11
由于您实际上将双精度转换为字符串,并将这些字符串附加到字符串流,您可以使用std::transform:
// your functor, transforming a double into a string
struct transform_one_double {
std::string operator()( const double& d ) const {
boost::format fmt( "%.3f " );
return (fmt % d).str();
}
};
// iteration code, taking each value and inserting the transformed
// value into the stringstream.
std::transform( vals.begin(), vals.end()
, std::ostream_iterator<std::string>( s, " ")
, transform_one_double() );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
933 次 |
| 最近记录: |