I have a function that essentially reads values in from a vector of doubles, appends these to a string (while ensuring a space between each and setting their precisions) and returns the end result, minus the final whitespace:
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 );
}
I would like to find out if this code could be simplified in any way. I have recently been investigating the use of for_each and functors in particular but have not been able to figure out how these techniques could improve this particular example.
Since you're actually transforming doubles into strings, and appending these strings to a stringstream, you can use std::transform for that:
// 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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With