c++ - 复制 std::string 时的分配

标签 c++ string stl

您认为哪种实现方式更好?

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

和...

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

区别在于第一个在默认构造函数之后使用reserve方法,而第二个使用接受字符数的构造函数。

编辑 1. 我不能使用 boost 库。 2. 我只是想比较 allocation-during-constructorallocation after-constructor

最佳答案

简单的怎么样:

std::string result;
result.reserve( source.length() );

std::transform( source.begin(), source.end(), 
                std::back_inserter( result ),
                ::toupper );

?

然后我个人会改用 boost。

关于c++ - 复制 std::string 时的分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5242925/

相关文章:

c++ - 在 C++ 中填充 C 结构的填充字节? (不涉及结构包装!)

c++ - 在 LLVM 中修改 CFG

c++ - 在 C++ 中静态构造函数的实现不起作用

php - 在 PHP 中使用 str_word_count 将数字作为单独的单词进行计数

c++ - tr1::result_of 的一个好的用例是什么?

c++ - Boost 图形库的性能 vertex_descriptor

java - java中如何从相互依赖的字符串中删除部分字符串数据

string - 如何检查字符串是否包含 Rust 中的子字符串?

c++ - 是否存在经过认证的(ISO 26262或类似的)C++标准库?

c++ - 当我们可以更有效地使用 vector 来实现优先级队列时,为什么要使用堆来实现它