//http://stackoverflow.com/questions/3780994/string-reversal-in-c

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

string test_string = " This   is my test    string";

int main() {
    typedef pair <string::size_type,string::size_type> word_boundaries;
    typedef vector <word_boundaries> word_boundaries_vector;
    word_boundaries_vector words, spaces;
    
	bool first_is_char = test_string[0] != ' ';

    for(string::size_type pos=0; pos != string::npos;) {
        bool is_char = test_string[pos] != ' ';
        string::size_type pos_end_token = string::npos;
        
        if (is_char)
            pos_end_token = test_string.find(' ', pos);
        else
            pos_end_token = test_string.find_first_not_of(' ',pos);
            
        //word_boundaries token = make_pair(pos,pos_end_token == string::npos ? string::npos : pos_end_token-pos);
        word_boundaries token;
        token.first = pos;
        token.second = pos_end_token == string::npos ? string::npos : pos_end_token-pos;
        
        if (is_char)
            words.push_back(token);
        else
            spaces.push_back(token);
        
        pos = pos_end_token;
    }
    
    stringstream ss;
    
    word_boundaries_vector::const_reverse_iterator it_w = words.rbegin();
    word_boundaries_vector::const_iterator it_s = spaces.begin();

    word_boundaries b;

	if (!first_is_char)
	{
        b = *it_s++;
		ss << test_string.substr(b.first,b.second);
    }
    
    while(it_w != words.rend() || it_s != spaces.end()) {
        if (it_w != words.rend()) {
            b = *it_w++;
            ss << test_string.substr(b.first,b.second);
        }
        if (it_s != spaces.end()) {          
            b = *it_s++;
		    ss << test_string.substr(b.first,b.second);
        }
    }
    
    string reversed = ss.str();
    cout << "Input: '" << test_string << "'" << endl << "Output: '" << reversed << "'" << endl;
}