So recently I got into a debate about how to solve a problem, the problem specifically was: How do I find all the pallindromes between 1 and 1 million. I said, “Use atoi to make a string, use a for loop to reverse the string, the use strcmp to compare the string(s) in question.
A few minutes later someone asked “Why would you use a C-style solution in C++.” I found myself confused of a simple, more “C++” way of solving this with code as direct and easy to understand. Anyone care to illuminate me on this one?
edit: itoa not atoi
Example C++ solution:
(I used
std::remove_copy_ifto make up for the lack ofstd::copy_ifwhich is in C++0x)For completeness sake I implemented a version that generates the palindromes rather than testing candidates against a predicate:
(I could have used boost.range I think instead of
std::mergefor this)The discussion point from this I guess then is “is this a better* way to write it?”. The thing I like about writing problems like the palindrome in this style is you get the “if it compiles it’s probably correct” heuristic on your side. Even if there is a bug it’ll still get handled sensibly at run time (e.g. an exception from
lexical_cast).It’s a markedly different way of thinking from C programming (but strangely similar to Haskell in some ways). It brings benefits in the form of lots of extra safety, but the compiler error messages can be terrible and shifting the way you think about problems is hard.
At the end of it all though what matters is “is it less work for less bugs?”. I can’t answer that without some metrics to help.
*For some definition of better.