【问题标题】:C++ std::find lambda expressionsC++ std::find lambda 表达式
【发布时间】:2013-05-28 02:15:25
【问题描述】:

在我的一生中,我无法让这段代码工作。在弃用 XNA 框架后,我正在尝试将我的代码从 C# 转换为 C++,但是一个顽固的方法不想被转换。在 C# 中是:

public Tile GetTileAtPosition(bool screenOrGame, Vector2 position)
    {

        if (screenOrGame)
        {
            return Array.Find(tileList, tile => tile.Position == position / 24);
        }
        else
        {
            return Array.Find(tileList, tile => tile.Position == position);
        }
    }

在 C++ 中,我尝试使用的代码是:

Tile Level::GetTileAtPosition(bool screenOrGame, sf::Vector2f position)
{
    vector<Tile>::iterator it;

    if (screenOrGame)
    {

        it = find(tileList.begin(), tileList.end(), [position](const Tile &t) { return t.GetPosition() == sf::Vector2f(position.x / 24, position.y / 24); });
        return Tile(it->GetID(), it->GetPosition().x, it->GetPosition().y);

    }

    else
    {

        it = find(tileList.begin(), tileList.end(), [position](const Tile& t) { return t.GetPosition() == position; });
        return Tile(it->GetID(), it->GetPosition().x, it->GetPosition().y);

    }

}

在 C++ 赋值行 (it = ...) 上,我遇到了一个我无法找出原因或解决方案的棘手错误。它返回:

error C2679: binary '==' : no operator found which takes a right-hand operand of type 'const Blobby::Level::GetTileAtPosition::<lambda_29eb981cd341d9c05d39c4654bc470b9>' (or there is no acceptable conversion)    c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility 3186

有什么方法可以修复这个错误,或者有更好/更实用的方法在 C++ 中实现该方法吗?

【问题讨论】:

    标签: c++ c++11 lambda find expression


    【解决方案1】:

    在 C++ 中,采用比较器的版本有时会以_if 为后缀。 std::find 就是这种情况。 std::find 采用要查找的元素,而 std::find_if 采用实现相等的比较器。该错误只是意味着它找不到与 lambda 等效的 Tile 的匹配项。

    【讨论】:

      猜你喜欢
      • 2013-04-28
      • 1970-01-01
      • 2011-04-22
      • 2023-01-20
      • 2022-01-19
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      相关资源
      最近更新 更多