九九乘法表 in C++ style

C++03

#include <iostream>

std::ostream& fun(std::ostream& out, int lhs, int rhs)
{
    return (!lhs || !rhs)? out: (out << lhs << "x" << rhs << "=" << (lhs * rhs) << "\n", rhs > 1? fun(out, lhs, rhs - 1): fun(out, lhs - 1, 9));
}

int main()
{
    fun(std::cout, 9, 9) << std::endl;
}

http://ideone.com/Q4zaVq

C++11 - try lambda recursive

#include <iostream>
#include <functional>
 
int main()
{
    std::function<std::ostream&(std::ostream&, int, int)> f;
    f = [&f](std::ostream& out, int lhs, int rhs) -> std::ostream&   {
        return (!lhs || !rhs) ? out : (out << lhs << "x" << rhs << "=" << (lhs * rhs) << "\n", rhs > 1 ? f(out, lhs, rhs - 1) : f(out, lhs - 1, 9));
    };
    f(std::cout, 9, 9) << std::endl;
}

http://ideone.com/uaYyhv

comments powered by Disqus