如何在 C 或 C++ 中交换 O(1) 时间复杂度中的两个字符串?

How to swap two strings in O(1) time complexity in C or C++?

提问人:Md. Saidul Islam 提问时间:3/1/2023 最后编辑:Md. Saidul Islam 更新时间:3/2/2023 访问量:270

问:

我想在不复制所有字符的情况下交换两个字符串,因为这需要更多时间。我认为使用字符串的地址可以在 O(1) 时间复杂度内完成。但我无法弄清楚。你能帮我做吗?

我尝试使用地址。但是存在一些语法错误。

#include <bits/stdc++.h>
using namespace std;

int main ()
{
  std::string buyer ("money");
  std::string seller ("goods");
  string *temp;
  
  std::cout << "Before the swap, buyer has " << buyer;
  std::cout << " and seller has " << seller << '\n';
  cout<< " Before the swap "<<(&buyer)<<" "<<(&seller)<<"\n";
  temp=(&buyer); (&buyer)=(&seller); (&seller)=temp;
  cout<< " After the address swap "<<(&buyer)<<" "<<(&seller)<<"\n";
  swap (buyer,seller);
  cout<< " After the built-in swap "<<(&buyer)<<" "<<(&seller)<<"\n";

  return 0;
}
C++ 字符串 指针 时间复杂度 传递引用

评论

8赞 NathanOliver 3/1/2023
您无法更改对象的地址。要交换两个字符串,请使用 或std::swapstd::string::swap
2赞 user253751 3/1/2023
(&buyer)=没有意义,就像说42=53;
1赞 Sam Varshavchik 3/1/2023
我有个激动人心的消息要告诉你:使用移动语义,这可以在 !O(1)
2赞 Yksisarvinen 3/1/2023
std::swap 已经是 O(1),所以不要再看了
3赞 273K 3/1/2023
当我看到 或 时,我会立即对问题投反对票。#include <bits/stdc++.h>using namespace std;

答:

1赞 Jeremy Friesner 3/1/2023 #1

正如评论者所指出的,在 O(1) 中可以做到你想要的(通过交换两个字符串中的指针成员变量,而不是通过复制字符串的字符),所以没有理由使用指针间接,除非可能作为一个学习练习。std::swap(buyer, seller)

因此,仅作为学习示例,以下是仅使用指针的方法:

#include <string>
#include <iostream>

int main ()
{
  std::string buyer ("money");
  std::string seller ("goods");

  std::string * temp1 = &buyer;
  std::string * temp2 = &seller;

  std::cout << "Before the swap, buyer has " << *temp1;
  std::cout << " and seller has " << *temp2 << '\n';

  // These three lines are equivalent to std::swap(temp1, temp2)
  std::string * temp3 = temp1;
  temp1 = temp2;
  temp2 = temp3;

  std::cout << "After the swap, buyer has " << *temp1;
  std::cout << " and seller has " << *temp2 << '\n';

  return 0;
}

评论

0赞 463035818_is_not_an_ai 3/2/2023
另一个好的学习练习可能是实现 EG 的交换。我的意思是交换指针总是很便宜,而且不需要复制O(1)struct foo { std::string value; };