Search code examples
c++sortinglambdastdpredicate

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


I want to compare my "WorldChunk" class functions "getX()" and "getY()" with "chunk_x" and "chunk_y" passed to function, but i don't want to create new instance of "WorldChunk" to compare with.

I've tried something like that but it doesn't work.

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 log:

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' 

Solution

  • The problem you're having is that you're trying to pass the comparison value through the lambda capture rather than through the parameters. Just do it correctly; there is no requirement that the type of the third parameter is the same type as the value_type of the iterators:

    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
    
    }
    

    Your real problem here is that lower_bound is not a generic search function (that's std::find). It requires that the loaded_chunk sequence is sorted (or at least partitioned against the test value) relative to the search function. That is, all elements for which the comparison against the value will be true must come before all elements for which the comparison against the value will be false. So unless you sorted this list of chunks by X/Y position (with that exact ordering; X < X, then Y < Y), this isn't going to work.