首页 > 解决方案 > 如何使用 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' 

标签: c++sortinglambdastdpredicate

解决方案


您遇到的问题是您试图通过 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),否则这是行不通的。


推荐阅读