Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there simpler way?

Tags:

c++

stl

I'd like to know if there is a shorter / simpler way to:

  1. Split the incoming string by words
  2. Write the tokens in reverse order to stdout

There are two restrictions: no libraries and no loops

#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <deque>

void list_string_elements(std::string s) {
    using namespace std;

    istringstream iss (s);
    deque<string> v;

    copy(istream_iterator<string>(iss), istream_iterator<string>(), front_inserter(v));

    copy(v.begin(),v.end(),ostream_iterator<string>(cout,"\n"));
}
like image 272
cimnine Avatar asked Aug 09 '11 12:08

cimnine


1 Answers

Slight abbreviation, we can get rid of a copy thanks to the iterator constructor of deque:

void list_string_elements(std::string s) {
    using namespace std;

    istringstream iss (s);
    deque<string> v(istream_iterator<string>(iss), (istream_iterator<string>()));
    copy(v.rbegin(),v.rend(),ostream_iterator<string>(cout,"\n"));
}

Note the extra parens around istream_iterator<string>(), to avoid a most vexing parse.

like image 108
Steve Jessop Avatar answered Oct 01 '22 12:10

Steve Jessop