find_if with lambda和捕获变量

时间:2017-12-05 13:13:47

标签: c++ c++11

我正在尝试解决骑士问题(在国际象棋中)并且我有以下代码用于骑士可以做出的所有可能的动作:

typedef vector<pair<int,int> > Path;

Path moves(const pair<int,int> & pos)
{

    Path allMoves = 
    {
        { (get<0>(pos))+1, (get<1>(pos))+2},
        { (get<0>(pos))+2, (get<1>(pos))+1},
        { (get<0>(pos))+2, (get<1>(pos))-1},
        { (get<0>(pos))+1, (get<1>(pos))-2},

        { (get<0>(pos))-1, (get<1>(pos))-2},
        { (get<0>(pos))-2, (get<1>(pos))-1},
        { (get<0>(pos))-2, (get<1>(pos))+1},
        { (get<0>(pos))-1, (get<1>(pos))+2}
    };

    return allMoves;
}

我希望使用以下条件对其进行过滤:

  • 方块在板内(没有负位置,不等于或超过板尺寸)
  • 方块不在给定路径

我尝试过以下操作:

Path legal_moves( const int size, Path visitedSquares, const pair<int,int> pos )
{

    Path possible_moves = moves(pos);

    auto legalMoves = find_if(  possible_moves.begin(),
                                possible_moves.end(),
                                []()
                                {

                                });

}

但是我不确定如何获得该对中的第一个元素(国际象棋棋盘上的x)和该对中的第二个元素(棋盘上的y)并检查条件。

如果不清楚,请将其评论出来。

感谢您的时间

1 个答案:

答案 0 :(得分:1)

你只需要在lambda中将d3.json gives me the editor error: "Property 'json' does not exist on type 'typeof "d3-ng2-service" (移动)作为à参数:

std::pair

您也可以使用auto legalMoves = find_if(possible_moves.begin(), possible_moves.end(), [](std::pair<int, int> const& a_move) { int x, y; std::tie(x, y) = a_move; // do whatever you want });

auto