rubenvb
rubenvb

Reputation: 76795

reversing a string in place

#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
bool compare( const string::size_type i, const string::size_type j )
{
    cout << "comparing " << i << " and " << j << "." << endl;
    return i < j;
}

void reverse_inplace( std::string &s )
{
    std::string::size_type i = 0;
    std::string::size_type j = s.size()-1;
    cout << "called" << endl;
    while( compare(i,j) );
    {
        cout << i << " " << j << endl;
        std::swap(s[i], s[j]);
        ++i;
        --j;
        cout << i << " " << j << endl;
    }
}

int main()
{
    string s( "a" );
    reverse_inplace(s);
    cout << s << endl;
}

What's wrong with my code? Why will it keep comparing, return true? and not execute the loop body there's no ? I tried GCC 4.6 and MSVC 10 SP1. The cout statements in the loop are not being executed for some strange reason.

Upvotes: 0

Views: 151

Answers (2)

MartinStettner
MartinStettner

Reputation: 29174

First, you need to remove the semicolon after the while statement.

Second, you should initialize j with s.size()-1, if not, it points to an invalid index at the beginning (1 in your case, which is after the end of the string). This can result in a number of unexpected results. Note, that you'll have to check for s.size()==0 in this case, since size_t is unsigned, and s.size()-1 would give an underflow for an empty string.

Third, you should have a look st std::reverse(), if you need this in production code :)

Upvotes: 2

FeifanZ
FeifanZ

Reputation: 16316

The loop body isn't being executed because you have a semicolon after the while() line, which is causing the loop body to be ignored. Therefore, the increment and decrement statements aren't being hit; neither are the couts.

Upvotes: 9

Related Questions