but how is it being reversed? |
Very inefficiently.
1 2 3 4 5 6 7 8 9 10
|
string reverse(string s)
{
string answer = "";
for(int i = 0 ; i < s.size(); i++)
{
answer = s[i] + answer;
}
return answer;
}
|
Consider what happens when reverse is fed a particular string, say "cab"
s.size() yields 3, so the for loop iterates 3 times.
The first time through the loop,
answer is an empty string. So we take
s[0] and prepend it to that empty string ( in effect 'c' + "".) At the conclusion of the first iteration of the loop,
answer is "c".
The second time through the loop
answer is "c". So we take
s[1] and prepend it to that string (in effect 'a' + "c") which means at the conclusion of the second iteration of the loop
answer is "ac".
The third time through the loop
answer is "ac". So we take
s[2] and prepend it to that string (in effect 'b' + "ac") which means at the conclusion of the third iteration of the loop
answer is "bac".
And that is what we return.