英语不好,但请理解。
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;
我正在使用这样的现有代码,有没有一种方法可以优化字符串?我认为这段代码做了很多无用的操作。有没有一种优化的方法?
最佳答案
您的问题是+ =,但您没有在任何地方使用+ =。您仅使用+。
“+”可能是连接字符串的最有效方法。还有其他方法,但是+不太可能恶化。
如John Bollinger所说,如果您需要做的只是输出连接结果,则直接输出片段:
cout << str_base << str_user_input << "\n [system message :]" << str_system_message << endl;
或使用C++ 20(如Thomas Sablik所说):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);
我建议尝试改为优化代码的其他部分(如果需要),因为它不太可能比语言/编译器做得更好。忘记优化+。从另一个 Angular 来看,请引用此问题的答案:
Efficient string concatenation in C++
关于c++ - 有什么方法可以优化c++字符串+ =运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63350848/