patterncppMinor
Towers of Hanoi redux
Viewed 0 times
towershanoiredux
Problem
Inspired by Mayur Kulkarni's question this morning, I decided to post some code for the classic Towers of Hanoi problem, but this time in C++. Since this is fairly "textbook" kind of task, all suggestions are welcome.
#include
#include
#include
#include
class Hanoi {
typedef std::vector Tower;
Tower a, b, c;
void show(std::string const &label, Tower c) {
std::cout (std::cout, "\t"));
std::cout input) : a(input) { dump(); }
void operator()() { MoveStack(a, c, b, a.size()); }
};
int main() {
Hanoi h { 30, 25, 20, 15, 10, 5 };
h();
}Solution
Here are just a few observations that may help you improve your code. In all, it is quite clean and easy to read and understand.
Use
The
Use
The constructor can easily determine the maximum size of the vectors. If there were much larger ones than this, one could avoid potentially costly memory reallocations by using
Prefer flexible output
This is admittedly a very simple program, but generally it's nice to allow for printing to any
Use all required
The code makes use of
However, as @Morwenn points out in a comment, it's not needed to include it explicitly since
Use
const where practicalThe
show() and dump() function don't (and shouldn't) alter the underlying object, so they should be declared const:void show(std::string const &label, Tower c) const;
void dump() const;Use
reserve() to prevent reallocationsThe constructor can easily determine the maximum size of the vectors. If there were much larger ones than this, one could avoid potentially costly memory reallocations by using
Tower.reserve() within the constructor.Prefer flexible output
This is admittedly a very simple program, but generally it's nice to allow for printing to any
std::ostream rather than having std::cout hardcoded into the class. Perhaps it could be a constructor argument.Use all required
#includesThe code makes use of
std::initializer_list but doesn't have this line:#include However, as @Morwenn points out in a comment, it's not needed to include it explicitly since
std::vector must necessarily already include it.Code Snippets
void show(std::string const &label, Tower c) const;
void dump() const;#include <initializer_list>Context
StackExchange Code Review Q#116312, answer score: 4
Revisions (0)
No revisions yet.