reverse strings in an array

I am trying to write a function that does the following:

int flip(string a[], int n);
Reverse the order of the elements of the array and return n. For example,

string beings[6] = { "jarjar", "belle", "", "r2d2", "maleficent", "yoda" };
int q = flip(beings, 4); // returns 4
// beings now contains: "r2d2" "" "belle" "jarjar" "maleficent" "yoda"

Last edited on
Try the following code (I did not test it)

1
2
3
4
5
6
7
8
9
10
11
int flip( std::string a[], int n )
{
   for ( std::string *first = a, *last = a + n; first != last && first != --last; ++first )
   {
      std::string t( *first );
      *first = *last;
      *last = t;
   }

   return ( n );
}



Of course the code inside the loop can be changed to

std::swap( *first, *last );
Last edited on
I figured it out by doing
1
2
3
4
5
6
7
8
9
10
int flip(string a[], int n)
{
	int j = n-1;
	for(int k = 0; j > k;j--, k++)
	{
		string temp = a[k];
		a[k] = a[j];
		a[j] = temp;
	}
}

appreciate the response though
Last edited on
You'll need a loop that iterates through both arrays without going out of bounds on either. I would start:
int loopAmount = (n1 < n2 ? n1 : n2);


Wrong thread... Wait, what?
Last edited on
Your code is invalid. Consider n equal to 3.:)

I am sorry. It seems I am wrong.:)
Last edited on
Topic archived. No new replies allowed.