This question has been done to death in SO:. Here is my version using STL functions of the tradition algorithm of reversing the string and then reversing the words. is there a more elegant soln without using loops?
std::string something;
std::getline(std::cin, something);
std::reverse(something.begin(), something.end());
for (size_t i = 0, size_t nextPos = something.find_first_of(' ', i);
nextPos != std::string::npos; i = nextPos + 1,
nextPos = something.find_first_of(' ', i)) {
std::string::iterator startIter = something.begin() + i;
std::string::iterator endIter = something.begin() + nextPos;
std::reverse(startIter, endIter);
}
Assume the input is perfect no space before and after sentence and exactly single space between words. Is there an stl solution that requires no loop?
Best,
Subramanian
Here’s a loop-free way using iterators and a closure:
Update: Here is an in-place algorithm with one single loop:
Example:
Test run: