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

How to DRY multiple consecutive for loops

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

    std::cout << color << "      " << "3[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] << "  " << "3[m";
}

std::cout << std::endl;

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

    std::cout << color << "      " << "3[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 << "       " << "3[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] << "  " << "3[m"    
}

std::cout << std::endl;

draw_blank();

但它看起来有点复杂,我直到循环写了两次。那么写一个所有3个循环都相同的结构并且只改变中间循环中的一个输出线是不是很愚蠢?

您可以像这样向您的 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 << "  3[m";
    }
    std::cout << std::endl;
};

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