str.erase( std::unique(str.begin(), str.end()), str.end());
This will work not only in spaces. For example, the string "aaabbbcccddd" will become "abcd". Is this what you want? If you just want to reduce the spaces to one place, you can pass the binary predicate as the third argument to std::unique , like this one:
bool BothAreSpaces(char lhs, char rhs) { return (lhs == ' ') && (rhs == ' '); }
source share