# 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 <iostream>
#include <utility>
#include <string>
#include <cctype>

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

template<typename BidirIt, typename IsSeparatorTester>
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 << test << std::endl;
reverse_words(test.begin(), test.end(), isspace);
std::cout << test << 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.

• You don't need the lamda. reverse_words(test.begin(), test.end(), isspace); will suffice. – Daan Jan 2 '15 at 18:01
• OK, fixed. If that's the only complaint, then it's a hell of an improvement from my first C++ attempt. :) – JT1 Jan 2 '15 at 18:07
• No need to write your own reverse. There is already a std::reverse() – Martin York Jan 2 '15 at 19:11
• @LokiAstari: Check my last comment after the code... – JT1 Jan 2 '15 at 21:01