Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
CodeJam 2010 thing Problem B: reverse words in strings.
//
// CodeJamRevWords - (c) 2013 by Arthur Langereis (@zenmumbler)
// Problem: http://code.google.com/codejam/contest/351101/dashboard#s=p1
//
// The easiest of the 2010 CodeJam problems. Shows using iterators in
// reverse and forward and how they interoperate using .base()
// Verified correct on the problem page.
//
#include <string>
#include <iostream>
std::string readLine() {
std::string s;
getline(std::cin, s);
return s;
}
int main() {
auto numTests = std::stol(readLine()), counter = 0L;
while (std::cin.good() && numTests--) {
auto source = readLine();
auto from = source.rbegin(),
to = source.rend();
std::cout << "Case #" << ++counter << ": ";
while (from != to) {
// find spaces or end-of-stream going backwards
auto nextSpace = std::find(from, to, ' ');
// copy the characters (without space) forwards into cout
// base returns fwd-iter to el after the one pointed to by the rev-iter
// this is good as we've selected a range starting with a space which
// we want to skip and the 2nd iterator of a pair always points to the
// el after the one you wish to process up to.
std::copy(nextSpace.base(), from.base(), std::ostream_iterator<char>(std::cout));
// continue searching beyond last space
from = nextSpace;
if (from != to) {
from++;
std::cout << ' ';
}
}
std::cout << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment