【问题标题】:String concatenation time complexity c++字符串连接时间复杂度 C++
【发布时间】:2018-01-06 01:23:32
【问题描述】:

我在 C++ 中搜索了连接字符串的不同方法,我发现 std::stringstream 和 std::string 是可能的选项。但是,我找不到字符串流和字符串的串联操作的时间复杂度。 C ++中字符串连接的时间复杂度是多少。此外,在 C++ 中的 std::stringstream 和 std::string 中转换为字符串的时间复杂度是多少。是否可以在 C++ 中以 0(1) 时间附加字符串?感谢您的宝贵时间。

【问题讨论】:

  • “时间复杂度”具有相同的 O(N) 阶。但是将两个std::string 对象加在一起会比使用std::stringstream 快很多。
  • 想一想:你不能因为需要复制而去亚线性;它一次一个字符。您也不能使用超线性,因为在连接期间没有嵌套循环。因此,O(n+m) 是唯一剩下的。
  • std::stringstream 但是在转换为字符串方面要好得多,对吧?
  • 将字符串转换为字符串?
  • 不,如果我有一个 int,那么 std::stringstream 是否更适合将 int 转换为字符串?

标签: c++ string time-complexity stringstream stdstring


【解决方案1】:

两者都未指定,但您可以猜测线性复杂度(创建新缓冲区,将字符复制到新缓冲区)。

【讨论】:

  • 否,但在 C++ 中,您可以同时附加到 std::string 和 std::stringstream ,所以在这种情况下它仍然是线性复杂度吗?
  • @VishwaPatel 是的。两者都在做几乎相同的事情,可能 stringstream 需要 2 个副本,但它仍然是线性时间。
  • 那么使用 std::string 进行追加和 std::stringstream 转换为字符串是否有效?
  • @VishwaPatel std::string 追加字符串字符串和 std::stringstream 用于“复杂”追加(如字符串整数、字符串浮点数)。
  • 非常感谢@amchacon
猜你喜欢
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多