Home > Software engineering >  find_if is not returning the expected output
find_if is not returning the expected output

Time:07-27

I am using find_if() to find the next higher value in a vector. It is returning the next index and not a higher value.

The input vector is:

vector<int> height = { 1,8,6,2,5,4,8,3,7 };

I am looking for the next highest value, starting at i=0, height[0] = 1. The code updates to set i=1, height[1] = 8. I expect to get i=7. I get i=2 instead.

for (size_t i = 0; i < height.size() - 1; i  )
{   
    auto res = std::find_if((height.begin()   i   1), height.end(),
        [&height, i](int x) {           
        return height[x] >= height[i];
    });
    auto higher_index = std::distance(height.begin(), res);

    if (res != height.end() && higher_index < height.size())
    {
        // found the next highest height
        // calculate new area and make i the same as highest height
        area = min(height[i], height[higher_index]) * (higher_index - i);
        maxA = max(maxA, area);
        i = higher_index - 1;
    }
}

CodePudding user response:

Your lambda should look like this

    [&height, i](int x) {           
        return x >= height[i];
    }

find_if passes the value of each element of the given sequence to the predicate. Not the index of each element.

CodePudding user response:

It seems you mean:

auto res = std::find_if((height.begin()   i   1), height.end(),
    [&height, i](int x) {           
    return x >= height[i];
});

Or, it will be simpler to write:

auto res = std::find_if((height.begin()   i   1), height.end(),
    [value = height[i]](int x) {           
    return x >= value;
});

Here is a demonstration program:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::vector<int> height = { 1, 8, 6, 2, 5, 4, 8, 3, 7 };

    for ( size_t i = 0; i < height.size(); i   )
    {
        auto it = std::find_if( std::next( std::begin( height ), i   1 ),
                                std::end( height ),
                                [value = height[i]]( const auto &x )
                                {
                                    return not ( x < value );
                                } );
    
        if ( it != std::end( height ) )
        {
            std::cout << "The next element is at position " 
                      << std::distance( std::begin( height ), it )
                      << " with the value " << *it << '\n';
        }
    }
}

The program output is

The next element is at position 1 with the value 8
The next element is at position 6 with the value 8
The next element is at position 6 with the value 8
The next element is at position 4 with the value 5
The next element is at position 6 with the value 8
The next element is at position 6 with the value 8
The next element is at position 8 with the value 7
  • Related