一般的なケースで、再帰をフラット コードに置き換えたい場合は、スタック (LIFO) を使用する必要があります。したがって、再帰アルゴリズムがある場合:
void print(std::string str, int depth)
{
if (depth == n) {
std::cout << str << std::endl;
return;
}
for (int i = 0; i < 10; ++i) {
char val[2] = { i + '0', 0 };
print(str + val + ", ", depth+1);
}
}
ローカル変数 (この場合は str と i) を保存して、LIFO ベースに変換できます。
struct StackItem {
StackItem(const std::string& ss, unsigned ii)
: str(ss), i(ii)
{}
std::string str;
int i;
};
void print_norec()
{
std::list< StackItem > stack;
stack.push_back(StackItem("", 0));
while (!stack.empty()) {
StackItem& current = stack.back();
if (stack.size() == n+1) {
std::cout << current.str << std::endl;
stack.pop_back(); // return from "recursive" function
continue;
}
if (current.i < 10) {
char val[2] = { current.i + '0', 0 };
// call "recursive" function
stack.push_back(StackItem(current.str + val + ", ", 0));
current.i++;
} else {
stack.pop_back(); // return from "recursive" function
}
}
}