Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find_if is not returning the expected output

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] is 1. The code updates to set i=1, height[1] = 8. I expect to get i = 7. I get i = 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


    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;
        }
    }

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading