首页 > 解决方案 > 如何从 std::vector 中搜索并返回项目

问题描述

在我目前的情况下,我有一个std::vector填充Vector3f对象(每个都有 x、y 和 z 值)充当网格顶点,我想获取我的玩家位置(也是 a Vector3f)并将其发送到一个可以在Vector3f前面提到的网格顶点向量中的对象并返回匹配的Vector3f,以便我可以访问它的 y 组件并使用它来设置玩家的高度。

我得到的最接近的是波纹管:

Vector3f Mesh::checkMeshVertices(Vector3f playerPos)
{
    return std::find(meshVertices.begin(), meshVertices.end(), playerPos) != meshVertices.end();
}

但是,这只会在匹配时返回 true,我希望能够返回Vector3f匹配的实际值。

标签: c++vectorstl

解决方案


返回值的类型是bool,而函数的返回类型是Vector3f

由于返回的类型不是引用类型,因此如果找到向量,您可以在调用者中使用其传递的参数。所以该函数可以只返回一个布尔值,如

bool Mesh::checkMeshVertices(Vector3f playerPos)
{
    return std::find(meshVertices.begin(), meshVertices.end(), playerPos) != meshVertices.end();
}

如果要返回对找到的对象的引用,则该函数应在未找到该对象的情况下引发异常。

例如

Vector3d & Mesh::checkMeshVertices(Vector3f playerPos)
{
    auto it = std::find(meshVertices.begin(), meshVertices.end(), playerPos);
    if ( it != meshVertices.end() ) return *it;
    else throw std::out_of_range();
}

推荐阅读