C++ 我什么时候应该使用字符串而不是字符串流?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12118899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:54:09  来源:igfitidea点击:

When should I use string instead of stringstream?

c++stringperformanceiostreamstringstream

提问by Lucas Lima

When should I use stringstreaminstead of string::append()? Supposing I'm going to catenate just strings.

我什么时候应该使用stringstream而不是string::append()?假设我将只连接字符串。

stringstream ss;
ss << str1 << "str2" << ...
Write(ss.str());

Or:

或者:

string str;
str.reserve(10000);
str.append(str1);
str.append("str2");
...
Write(str);

Which of them is faster?

他们中谁更快?

采纳答案by Praetorian

I don't know which one will be faster, but if I had to guess I'd say your second example is, especially since you've called the reservemember function to allocate a large space for expansion.

我不知道哪个会更快,但如果我不得不猜测我会说你的第二个例子是,特别是因为你已经调用了reserve成员函数来分配一个大空间进行扩展。

If you're only concatenating strings use string::append(or string::operator+=).

如果您只是连接字符串,请使用string::append(或string::operator+=)。

If you're going to convert numbers to their string representation, as well as format them during conversion, and then append the conversion results together, use stringstreams. I mention the formatting part explicitly because if you do not require formatting C++11 offers std::to_stringwhich can be used to convert numeric types to strings.

如果您要将数字转换为其字符串表示形式,并在转换期间对其进行格式化,然后将转换结果附加在一起,请使用 stringstreams。我明确提到了格式化部分,因为如果您不需要格式化 C++11 提供的std::to_string可用于将数字类型转换为字符串的产品。

回答by anio

string.append is much faster. Especially when you reserve.

string.append 快得多。尤其是当您预订时。

If you are concatenating only strings, I would use string.append. I would only use stringstream when I need to automatically convert non-strings to strings for example:

如果您只连接字符串,我会使用 string.append。我只会在需要自动将非字符串转换为字符串时使用 stringstream,例如:

const int x(42);
stringstream ss;
ss << "My favorite number is: " << x << std::endl;

Here stringstream automatically converts x to a string and appends it. I do not need to call atoi. Stringstream will convert all the basic types automatically for you. It is great for that purpose.

这里 stringstream 自动将 x 转换为字符串并附加它。我不需要打电话给 atoi。Stringstream 将为您自动转换所有基本类型。这非常适合这个目的。

Also if you are only going to be directing data into the stringstream to convert it to a string later. You can use ostringstream which is for output.

此外,如果您只想将数据导入 stringstream 以稍后将其转换为字符串。您可以使用用于输出的 ostringstream 。

I hope that helps.

我希望这有帮助。