如何干掉多个连续的for循环

时间:2016-05-05 08:16:55

标签: c++ dry

for (int j = 0; j < BOARD_SIZE; ++j)
{
    setcolor(m_board[i][j]);

    std::cout << color << "      " << "\033[m";
}

std::cout << std::endl;

for (int j = 0; j < BOARD_SIZE; ++j)
{
    setcolor(m_board[i][j]);

    std::cout << color << "  " << m_board[i][j] << "  " << "\033[m";
}

std::cout << std::endl;

for (int j = 0; j < BOARD_SIZE; ++j)
{       
    setcolor(m_board[i][j]);

    std::cout << color << "      " << "\033[m"; 
}

std::cout << std::endl;

这就是我的代码(它们都嵌套在另一个for循环中,因此i)。第一个和最后一个循环是相同的,而中间的循环只是通过输出变量而不是仅输出空格而不同。我尝试将顶部和底部循环放入lambda,如下所示:

auto draw_blank = [&]()
{
    for (int j = 0; j < BOARD_SIZE; ++j)
    {
        setcolor(m_board[i][j]);

        std::cout << color << "       " << "\033[m";
    }
    std::cout << std::endl;
};

draw_blank();

for (int i = 0; i < BOARD_SIZE; ++i)
{
    setcolor(m_board[i][j]);

    std::cout << color << "  0" << m_board[i][j] << "  " << "\033[m"    
}

std::cout << std::endl;

draw_blank();

但它看起来有点复杂,我直到两次写循环。那么编写一个对所有3个循环都相同的结构并且仅改变中间循环中的一个输出行是不是很有用呢?

1 个答案:

答案 0 :(得分:2)

您可以像这样在lambda中添加一个参数:

auto draw_board = [&](bool clear)
{
    for (int j = 0; j < BOARD_SIZE; ++j)
    {
        setcolor(m_board[i][j]);

        std::cout << color << "  ";
        if (clear)
        {
            std::cout << "  ";
        }
        else
        {
            std::cout << m_board[i][j];
        }

        std::cout << "  \033[m";
    }
    std::cout << std::endl;
};

draw_board(true);
draw_board(false);    
draw_board(true);