Nov 7, 2012 at 8:51pm UTC
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 Nov 7, 2012 at 9:24pm UTC
Nov 7, 2012 at 9:22pm UTC
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 Nov 7, 2012 at 9:24pm UTC
Nov 7, 2012 at 9:26pm UTC
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 Nov 7, 2012 at 9:27pm UTC
Nov 7, 2012 at 9:28pm UTC
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 Nov 7, 2012 at 9:33pm UTC
Nov 7, 2012 at 9:28pm UTC
Your code is invalid. Consider n equal to 3.:)
I am sorry. It seems I am wrong.:)
Last edited on Nov 7, 2012 at 9:30pm UTC