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
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.