如何使用std::lower_bound比较对象变量,而不使用第二个对象进行比较

How to use std::lower_bound to compare object variables without second object to compare with

本文关键字:比较 对象 第二个 lower bound 何使用 变量 std      更新时间:2023-10-16

我想将我的"WorldChunk"类函数"getX(("answers"getY(("与传递给函数的"chunk_x"answers"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捕获而不是参数传递比较值。只要做得正确;不要求第三个参数的类型与迭代器的CCD_ 1的类型相同:

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序列进行排序(或至少根据测试值进行分区(。也就是说,与值的比较为true的所有元素必须位于与值的对比为false的所有元素之前。因此,除非你按X/Y位置对这个块列表进行排序(按照确切的顺序;X<X,然后Y<Y(,否则这是行不通的。