在我目前的情况下,我有一个 std::vector
,其中填充了 Vector3f
对象(每个对象都有 x、y 和 z 值)作为网格顶点,我想获取我的玩家位置(也是一个 Vector3f
)并将其发送到一个函数,该函数可以在前面提到的网格顶点 vector 中的 Vector3f
对象中搜索马赫并返回匹配的Vector3f
,这样我就可以访问它的 y 分量并用它来设置玩家高度。
我得到的最接近的是以下内容:
Vector3f Mesh::checkMeshVertices(Vector3f playerPos)
{
return std::find(meshVertices.begin(), meshVertices.end(), playerPos) != meshVertices.end();
}
但是,这只会在匹配时返回 true,我希望能够返回匹配的实际 Vector3f
。
最佳答案
返回值类型为bool
,函数返回类型为Vector3f
。
由于返回的类型不是引用类型,因此如果找到 vector ,您可以在调用方中使用其传递的参数。所以该函数只能返回一个 bool 值,例如
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();
}
关于c++ - 如何从 std::vector 搜索并返回项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60084191/