{
std::string s = "this is a string ";
std::string res = std::string();
int sLength = s.length();
for(int i = 0; i < sLength; i++)
res += s[i];
}
我认为这个 C++ 的复杂度是严格线性的(关于字符分配),而不是 C# 中的等价物的二次复杂度。
然而,事实上,在这种情况下,内存没有预先分配,我们实际上也在考虑二次复杂度吗?如果是,分配 char 数组会帮助我们实现线性复杂度吗?
最佳答案
您可以通过调用 std::string::reserve 来实现线性复杂度。这将防止随着字符串的增长而重新分配:
std::string s = "this is a string ";
std::string res = "what is this? ";
res.reserve(s.length() + res.length());
for(int i = 0; i < s.length(); i++)
res += s[i];
显然,您不会在现实生活中像这样连接字符串。
关于c# - 我可以在不分配的情况下实现线性(或接近)复杂的字符串连接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30399553/