C++中字符串拼接的时间和空间复杂度是什么?

huangapple go评论84阅读模式
英文:

Time and Space complexity of String Concatenation in C++

问题

x = x + x
x += x
x.append(x)

上面的三种方法是否相同(考虑时间和空间复杂性)?

我认为使用 "+" 会创建一个新字符串,而 "append" 只是将内容添加到现有字符串,因此 "append" 更快且占用更少的空间。

这是一个更偏向理论和知识的问题...

英文:
x = x+x
x+=x
x.append(x)

Are the three ways above the same (thinking of time and space complexity)

I’m thinking using “+” creates a new string while append just adds to the existing string, so append is faster and less space usage.

This is a questions that is more theory/knowledge based...

答案1

得分: 2

你正在调用三个(实际上是四个)不同的函数:operator=(s)operator+(s)operator+=(s)append(s),时间和空间要求(以及相关问题)将取决于这些函数的确切代码。对于你的问题,没有通用的答案。即使对于像 std::string 这样的给定类,它也取决于具体的实现。

请注意,在第一种情况中(x=x+x),你执行了两个操作(也就是调用了两个函数)。还要注意,operator=(s)operator+=(s)append(s) 直接作用于主对象的引用(我指的是 this,而不是额外的参数)。operator+=(s)append(s)参考手册中说明:“复杂性:没有标准的复杂性保证,典型的实现行为类似于 std::vector::insert。”

如果“追加”()之所以更快,是因为它“只是添加到现有字符串”,那么如果“现有字符串”有保留的空间(这不是情况)可能是正确的。

英文:

You're calling three (actually four) different functions: operator=(s), operator+(s), operator+=(s) and append(s), and the time and space requirements (and concerns) will depend on the exact code of these functions. There's no generic answer to your question. Even for a given class, like std::string, it would be implementation dependant.

Please note that in the first case (x=x+x), you're doing two operations (that is, calling two functions). And also note that operator=(s), operator+=(s) and append(s) act directly on a reference to the main object (I'm talking about the this, and not about the additional parameter). The reference manual for operator+=(s) and append(s) states "Complexity: There are no standard complexity guarantees, typical implementations behave similar to std::vector::insert."

The idea of append() being faster because it "just adds to the existing string" could be right if the "existing string" had reserved space (which is not the case).

huangapple
  • 本文由 发表于 2023年2月19日 01:41:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定