HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Reversing the "words" of a container with a bidirectional iterator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theiteratorcontainerwithwordsbidirectionalreversing

Problem

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 
#include 
#include 
#include 

template
void my_reverse(BidirIt first, BidirIt last)
{
  for(--last; first 
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.

Solution

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.

Context

StackExchange Code Review Q#75504, answer score: 5

Revisions (0)

No revisions yet.