有什么方法可以优化 c++ 字符串 += 运算符? [英] Is there any way to optimize c++ string += operator?

查看:73
本文介绍了有什么方法可以优化 c++ 字符串 += 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

英文不好,请理解.

string str;
string str_base = "user name = ";
string str_user_input;
string str_system_message;
...

str = str_base + str_user_input + "\n [system message :]" + str_system_message;

cout << str << endl;

我正在使用这样的现有代码,有没有办法优化字符串?

I'm using the existing code like this, is there a way to optimize string?

我认为这段代码做了很多无用的操作.有没有优化的方法?

I think this code does a lot of useless operations. Is there a way to optimize?

推荐答案

你的问题是 +=,但你并没有在任何地方使用 +=.您只使用了 +.

Your question says +=, but you're not using += anywhere. You are using only +.

+"可能是连接字符串最有效的方法.还有其他方法,但 + 不太可能更糟.

"+" is probably the most efficient way to concatenate strings. There are other ways, but it is unlikely that + is worse.

正如 John Bollinger 所说,如果您需要做的只是输出连接的结果,那么直接输出片段:

As John Bollinger said, If all you need to do is output the concatenated result, then output the pieces directly:

cout << str_base << str_user_input << "\n [system message :]" << str_system_message << endl;

或者使用 C++20(正如 Thomas Sablik 所说):

Or with C++20 (as Thomas Sablik says):

std::format("{}{}\n [system message :]{}", str_base, str_user_input, str_system_message); otherwise: fmt::format("{}{}\n [system message :]{}", str_base, str_user_input, str_system_message);

我建议您尝试优化代码的其他部分(如果需要),因为您不太可能比语言/编译器做得更好.忘记优化 +.

I would suggest trying to optimize other parts of your code instead (if you need to), since its unlikely you can do better than the language / compiler. forget about optimizing +.

换个角度看这个问题的答案:

For another perspective, please refer to the answer for this question:

C++ 中的高效字符串连接

这篇关于有什么方法可以优化 c++ 字符串 += 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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