#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void ReverseWordOrder(string& phrase)
{
	// First, reverse the string character by character
	reverse(phrase.begin(), phrase.end());
	
	// Now, go through and reverse each space delimited word in the string, so they get double-reversed
	// And end up being oriented in the right direction
	size_t wordStart = -1;
	for(size_t i = 0; i < phrase.length(); ++i)
	{
		// Handles finding the start index in case of multiple spaces in a row
		if (wordStart == -1 && phrase[i] != ' ')
			wordStart = i;

		// If we found a letter before and are now finding a space...
		else if (wordStart != -1 && phrase[i] == ' ')
		{
			// ...reverse that sequence of characters.
			reverse(phrase.begin() + wordStart, phrase.begin() + i);
			wordStart = -1;
		}
	}
	
	// If string doesn't end in a space
	if (wordStart != -1) 
		reverse(phrase.begin() + wordStart, phrase.end());
	
}

int main()
{
	string str = "Apples bananas and  oranges";
	ReverseWordOrder(str);
	cout << str << endl;
	return 0;
}