c++ - 如何使用 std::lower_bound 在没有第二个对象的情况下比较对象变量
问题描述
我想将我的“WorldChunk”类函数“getX()”和“getY()”与传递给函数的“chunk_x”和“chunk_y”进行比较,但我不想创建“WorldChunk”的新实例来比较.
我已经尝试过类似的方法,但它不起作用。
int ChunkGrid::unload_chunk(unsigned int chunk_x, unsigned int chunk_y)
{
auto chunk = std::lower_bound(loaded_chunks.begin(), loaded_chunks.end(), NULL,
[chunk_x, chunk_y](const WorldChunk& ch, const auto * null)
{
return (ch.getX() == chunk_x && ch.getY() == chunk_y) ? true : false;
});;
//rest of the function
}
错误日志:
Error C2672 'operator __surrogate_func': no matching overloaded function found.
Error C2784 'auto ChunkGrid::unload_chunk::<lambda_d0b216222e2c66d42cf1e3316f6d68ac>::operator ()(const WorldChunk &,const _T1 *) const': could not deduce template argument for 'const _T1 *' from 'const _Ty'
解决方案
您遇到的问题是您试图通过 lambda 捕获而不是通过参数传递比较值。只要正确地做;不要求第三个参数的类型与value_type
迭代器的类型相同:
int ChunkGrid::unload_chunk(vec2<unsigned int> chunk_loc)
{
auto chunk = std::lower_bound(loaded_chunks.begin(), loaded_chunks.end(), chunk_loc,
[](const WorldChunk& ch, const vec2<unsigned int> &loc)
{
return (ch.getX() < loc.x && ch.getY() < loc.y) ? true : false;
});;
//rest of the function
}
您真正的问题是这lower_bound
不是通用搜索功能(即std::find
)。它要求loaded_chunk
相对于搜索功能对序列进行排序(或至少根据测试值进行分区)。也就是说,与值比较为真的所有元素必须在与值比较为假的所有元素之前。因此,除非您按 X/Y 位置对这个块列表进行排序(使用确切的顺序;X < X,然后 Y < Y),否则这是行不通的。
推荐阅读
- javascript - 无法将数据插入到 SMS 分发的模板文字中
- r - 如何找到对应于最大值的值并在R中标记它
- apache-kafka - 当我在 Kafka 主题上生成消息时,我可以期待哪些可能的异常?
- deep-learning - 如何创建集中图层?
- android-studio - Android Studio 4.2 Canary 无线调试不工作
- flutter - 我如何/在哪里将自定义动画浮动操作按钮放在主页/内容的顶部?扑
- reactjs - React State 变量没有更新
- javascript - 取消卸载时的 API 调用
- hadoop - Dask:从 HDFS 读取时,pyarrow/hdfs.py 返回 OSError: Getting symbol hdfsNewBuilder failed
- c# - 对象关系 C#