std :: string :: assign与std :: string :: operator = [英] std::string::assign vs std::string::operator=

查看:233
本文介绍了std :: string :: assign与std :: string :: operator =的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很早以前就用Borland C ++编写代码,现在我正试图理解新(对我)C + 11(我知道,我们在2015年,有一个c + 14 ...但是我'正在从事C ++ 11项目)

I coded in Borland C++ ages ago, and now I'm trying to understand the "new"(to me) C+11 (I know, we're in 2015, there's a c+14 ... but I'm working on an C++11 project)

现在,我有几种方法可以给字符串赋值。

Now I have several ways to assign a value to a string.

#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+个结构,而我正在寻找最快的机制(我不关心内存,除非有很大的不同)

They both work. I learned from http://www.cplusplus.com/reference/string/string/assign/ that there are another ways to use assign . But for simple string assignment, which one is better? I have to fill 100+ structs with 8 std:string each, and I'm looking for the fastest mechanism (I don't care about memory, unless there's a big difference)

推荐答案

两者都同样快,但是 = ... 更清晰。

Both are equally fast, but = "..." is clearer.

但是,如果您确实想要快速,请使用 assign 并指定大小:

If you really want fast though, use assign and specify the size:

test2.assign("Hello again", sizeof("Hello again") - 1); // don't copy the null terminator!
// or
test2.assign("Hello again", 11);

这样,只需要进行一次分配即可。 (您还可以预先 .reserve()足够的内存来获得相同的效果。)

That way, only one allocation is needed. (You could also .reserve() enough memory beforehand to get the same effect.)

这篇关于std :: string :: assign与std :: string :: operator =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆