【问题标题】:C++: Reverse Strings within an array. Swap strings between two different arraysC++:在数组中反转字符串。在两个不同的数组之间交换字符串
【发布时间】:2012-03-09 00:57:12
【问题描述】:

我已经为这段代码编写了主干。我只需要对如何完成这些功能有一点了解。我认为a.swap(b) 可以在同一个数组中交换两个字符串。我错了吗?

感谢任何见解/建议。

#include <string>
using std::string;
#include <iostream>
#include <cassert>

using namespace std;

void swap(string & a, string & b); // swaps two strings.
void reverse_arr(string a1[], int n1); // reverse an array of strings.
void swap_arr(string a1[], int n1, string a2[], int n2); // swaps two arrays of strings.

int main(){
  string futurama[] = { “fry”, “bender”, “leela”, 
                        “professor farnsworth”, “amy”, 
                        “doctor zoidberg”, “hermes”, “zapp brannigan”, 
                        “kif”, “mom” };

  for (int i=0;i<10;i++)
    cout << futurama[i] << endl;

  swap(futurama[0],futurama[1]);
  cout << “After swap(futurama[0],futurama[1]);” << endl;

  for (int i=0;i<10;i++)
    cout << futurama[i] << endl;

  reverse_arr(futurama,10);
  cout << “After reverse_arr(futurama,10);” << endl;

  for (int i=0;i<10;i++)
    cout << futurama[i] << endl;

  // declare another array of strings and then 
  // swap_arr(string a1[], int n1, string a2[], int n2);

  char w;
  cout << “Enter q to exit.” << endl;
  cin >> w;
  return 0;
}

void swap(string & a, string & b){
  // swaps two strings.
  a.swap(b);
}

void reverse_arr(string a1[], int n1) {

// Reverse an array of strings.

}

void swap_arr(string a1[], int n1, string a2[], int n2) {

// swaps two arrays of strings.

}

【问题讨论】:

  • 如果“我错了吗?”是你的全部问题,这可能会被关闭。您对此代码是否有特定问题?它在工作吗?如果没有,具体是什么没有达到您的预期?我们非常乐意帮助您完成作业,但您至少应该提出有意义的问题。一个模糊的“我错了吗?”没有别的没有帮助(或试图自己解决它的迹象)。

标签: c++ arrays string reverse


【解决方案1】:

std::string::swap 函数肯定会交换数组中的两个字符串...它执行与std::swap 完全相同的功能。话虽如此,由于std::string 对象实际上是通过指针管理动态分配的字符串,所以swap 的STL 版本实际上不会交换内存块。因此,用于交换实际数组的函数必须在数组中递增并为每个元素调用 swap。例如:

void swap_arr(string a1[], int n1, string a2[], int n2) 
{
    for (int i=0; i < min(n1, n2); i++)
    {
        swap(a1[i], a2[i]);
    }
}

对于您的reverse_arr 函数,您可以执行非常相似的操作,但只需通过一半数组(比枢轴位置少一个槽,可以是一个元素,也可以是两个元素之间),而不是整个数组,否则你要把所有东西都换回原来的位置。

【讨论】:

  • 作业题请不要提供代码解决方案;它破坏了整个学习过程。如果您提供指导以引导提问者朝着正确的方向自行解决问题(特别是在包含大量代码并询问“这行得通吗?”或“这对吗?”而没有任何迹象的情况下,那就更好了他们甚至首先尝试了代码)。如果您帮助他们学习而不是提供复制/粘贴解决方案,那么对于询问的人(以及将来可能必须维护他们编写的代码的其他人)来说会更好。 :)
猜你喜欢
  • 2012-01-18
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
相关资源
最近更新 更多