简体   繁体   中英

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

I've written the backbone for this code. I just needed a little insight on how i would complete the functions. i figure that a.swap(b) would work for swaping two strings within the same array. Am i wrong?

Any insight/ suggestions are appreciated.

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

}

The std::string::swap function will definitely swap two strings within an array ... it performs the exact same function as std::swap . That being said, since a std::string object actually is managing a dynamically allocated character string via pointers, the STL's versions of swap will not actually swap memory blocks. Therefore your function for swapping actual arrays will have to increment through the array and call swap for each element. For instance:

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]);
    }
}

For your reverse_arr function, you can do something very similar, but just make a pass through half the array (one slot less than the pivot position, which can either be an element, or between two elements), rather than the entire array, or else you're going to swap everything back into it's original position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM