gpt4 book ai didi

c++ - 简化 FOR 循环

转载 作者:太空狗 更新时间:2023-10-29 23:22:41 25 4
gpt4 key购买 nike

我有一个函数,它本质上是从一个 double vector 中读取值,将它们附加到一个字符串(同时确保每个值之间有一个空格并设置它们的精度)并返回最终结果,减去最后的空格:

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 );
}

我想知道是否可以以任何方式简化这段代码。我最近一直在研究 for_each 和仿函数的使用,但一直无法弄清楚这些技术如何改进这个特定示例。

最佳答案

由于您实际上是将 double 转换为字符串,并将这些字符串附加到字符串流中,因此您可以为此使用 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() );

关于c++ - 简化 FOR 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1399275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com