Making uppercase of std::string

Posted by Daniel K. on Stack Overflow See other posts from Stack Overflow or by Daniel K.
Published on 2011-03-09T08:06:52Z Indexed on 2011/03/09 8:10 UTC
Read the original article Hit count: 208

Filed under:
|
|

Which implementation do you think is better?

std::string ToUpper( const std::string& source )
{
    std::string result;
    result.reserve( source.length() );
    std::transform( source.begin(), source.end(), result.begin(), 
        std::ptr_fun<int, int>( std::toupper ) );
    return result;
}

and...

std::string ToUpper( const std::string& source )
{
    std::string result( source.length(), '\0' );
    std::transform( source.begin(), source.end(), result.begin(), 
        std::ptr_fun<int, int>( std::toupper ) );
    return result;
}

Difference is that the first one uses reserve method after the default constructor, but the second one uses the constructor accepting the number of characters.

© Stack Overflow or respective owner

Related posts about c++

Related posts about string