Reversing the "words" of a container with a bidirectional iterator I posted another snippet of code a few weeks back when I started learning C++. Here's my second try now that I have some time to play with this again. The goal is to write a generic algorithm for reversing the "words" of a container with a bidirectional iterator. Separators of words are any values that a functor parameter deems as a separator.

#include &lt;iostream&gt;
#include &lt;utility&gt;
#include &lt;string&gt;
#include &lt;cctype&gt;

template&lt;typename BidirIt&gt;
void my_reverse(BidirIt first, BidirIt last)
{
  for(--last; first &lt; last; ++first, --last)
    std::swap(*first, *last);
}

template&lt;typename BidirIt, typename IsSeparatorTester&gt;
void reverse_words(BidirIt first, BidirIt last, IsSeparatorTester issep)
{
  my_reverse(first, last);

  for(auto it = first; it != last; ++it) {
    if(issep(*it)) {
      my_reverse(first, it);
      first = it;
      ++first;
    }
  }

  // we bail out of the loop before inverting last word
  my_reverse(first, last);
}

int main()
{
  std::string test { " this   is a   test   " };
  std::cout &lt;&lt; test &lt;&lt; std::endl;
  reverse_words(test.begin(), test.end(), isspace);
  std::cout &lt;&lt; test &lt;&lt; std::endl;
  return 0;
}


As a comment, I know that STL has a reverse procedure, but I wanted to try to implement something similar myself.
Although not relevant to the algorithm itself, you could still consider these basic things:


It's best to use "\n" instead of std::endl for newlines.
You don't need a return 0 at the end of main(); it will do this for you automatically.
You should also add curly braces in my_reverse() for consistency and in case you'll need to add more to the loop.
The name IsSeparatorTester issep seems odd as an argument. Perhaps it should be renamed to something like Separator sep since it's not performing an action (like a function) and should therefore be a noun.

However, if you're mostly trying to reimplement std::reverse(), then you can leave it out this argument altogether.  There may not be many cases in which the user would choose something other than a space as a separator.