À la STL find_range()

I started by writing some code for the typical interviewee question and ended up factoring out part of it in a function I called find_range:


template <typename BidirectionalIterator_t, typename Predicate_t>

pair<BidirectionalIterator_t, BidirectionalIterator_t> find_range(BidirectionalIterator_t first, 
                                                                  BidirectionalIterator_t last,

                                                                  Predicate_t             predicate) {

   first = find_if(first, last, predicate);

   pair<BidirectionalIterator_t, BidirectionalIterator_t> result(first,first);

   if (result.first != last) {

      result.second++;

      result.second = find_if_not(result.second, last, predicate);

   }

   return result;

}


 

With it, writing a ReverseWords function becomes much more elegant:


void ReverseWords(wstring & s) { 
   pair<wstring::iterator, wstring::iterator> word;

   word.first = s.begin();

   while (word.first != s.end()) {

      word = find_range(word.first, s.end(), [] (wchar_t ch) {return !iswspace(ch);});

      reverse(word.first, word.second);

      word.first = word.second;

   }

}


 

Joyeux Noël!

 

 

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s