C++:反转数组中的字符串.在两个不同的数组之间交换字符串

C++: Reverse Strings within an array. Swap strings between two different arrays

本文关键字:字符串 数组 两个 交换 之间 C++      更新时间:2023-10-16

我已经为这段代码编写了主干。我只需要对如何完成这些功能有一点了解。我认为CCD_ 1将用于交换同一数组中的两个字符串。我错了吗?

如有任何见解/建议,我们将不胜感激。

#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.
}

std::string::swap函数肯定会交换数组中的两个字符串。。。它执行与CCD_ 3完全相同的功能。也就是说,由于std::string对象实际上是通过指针管理动态分配的字符串,所以STL版本的swap实际上不会交换内存块。因此,用于交换实际数组的函数必须在数组中递增,并为每个元素调用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函数,您可以做一些非常类似的事情,但只需穿过一半数组(比枢轴位置少一个槽,可以是一个元素,也可以是两个元素之间),而不是整个数组,否则您将把所有东西都交换回原来的位置。