4
\$\begingroup\$

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.

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

Although not relevant to the algorithm itself, you could still consider these basic things:

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.