我很久以前用Borland C ++编写,现在我正在尝试理解“新”(对我而言)C + 11(我知道,我们在2015年,有一个c + 14 ...但我正在工作在C ++ 11项目上)
现在我有几种方法可以为字符串赋值。
#include <iostream>
#include <string>
int main ()
{
std::string test1;
std::string test2;
test1 = "Hello World";
test2.assign("Hello again");
std::cout << test1 << std::endl << test2;
return 0;
}
他们都工作。我从http://www.cplusplus.com/reference/string/string/assign/那里了解到还有另外一种方法可以使用assign
。但对于简单的字符串赋值,哪一个更好?我必须用8 std:string填充100多个结构,我正在寻找最快的机制(我不关心内存,除非有很大的区别)
两者都同样快,但= "..."
更清晰。
如果你真的想要快速,请使用assign
并指定大小:
test2.assign("Hello again", sizeof("Hello again") - 1); // don't copy the null terminator!
// or
test2.assign("Hello again", 11);
这样,只需要一次分配。 (你也可以预先给.reserve()
足够的记忆以达到同样的效果。)