c++ - 如何从 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
匹配的实际值。
解决方案
返回值的类型是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();
}
推荐阅读
- python - 熊猫日期发生变化时如何减去时间?
- angular - ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改...以前的值:'ngIf:false'。当前值:'ngIf: true'
- math - 球与天花板的碰撞时间
- mercurial - Hg:复制文件而不保存历史记录(复制为新文件)
- python - 为什么在 Windows 10 下启动 python 如此缓慢,以及如何加快速度
- strapi - 如何用strapi纠正nginx conf
- c++ - 为什么 boost::bind 坚持将 `boost::placeholders` 拉入全局命名空间?
- javascript - JavaScript 类:(this 的实例)
- angular - angulartics2 自定义事件被发送到 facebook 但不发送到谷歌分析
- javascript - 第三个框锁定值JS