【发布时间】:2020-11-30 16:28:53
【问题描述】:
英文不好,但请理解。
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;
我正在使用这样的现有代码,有没有办法优化字符串?
我认为这段代码做了很多无用的操作。有没有办法优化?
【问题讨论】:
-
是的,使用
std::ostringstream -
@Andy 上次我用 stringstream 和 string::operator+ 比较了连接的性能,后者更快。每次人们不相信我时,他们都会比较自己并得到相同的结果。也许我们做错了什么,但没有人能告诉我 stringstream 更好。
-
如果你只想输出拼接结果,那么直接输出碎片即可:
cout << str_base << str_user_input << "\n [system message :]" << str_system_message << endl; -
使用 C++20:
std::format("{}{}\n [system message :]{}", str_base, str_user_input, str_system_message);否则:fmt::format("{}{}\n [system message :]{}", str_base, str_user_input, str_system_message); -
为什么要优化这个特定的代码?它是否在分析过程中显示为重要的处理瓶颈?
cout电话可能比这里的任何其他线路都贵得多。
标签: c++ string optimization operator-keyword