Atanu Atanu - 10 days ago 5
C++ Question

why std::max_element over std::map within some lower_bound not working?

I am not sure why the following snippet is not working:
The

lower_bound
call return the key 7, which is expected. Then the
std::max_element
between
begin()
and
lower_bound()
iterator should return 6, as it should search between key 4 and key 7 and the max value is 6 for key 7.
But it's returning the last
pair(15, 12)
for some reason which I can't figure out.

bool cmp(const std::pair<T, T>& p1, const std::pair<T, T>& p2)
{
return p1.second < p2.second;
}

int main()
{
std::map< T, T, std::greater<T> > store;
std::map< T, T, std::greater<T> >::iterator found_max, lower;

store[ 4 ] = 2;
store[ 7 ] = 6;
store[ 10 ] = 2;
store[ 15 ] = 12;
lower = store.lower_bound( 8 );

printf("%ld %ld\n", lower->first,lower->second);

found_max = std::max_element(store.begin(), lower, cmp);
printf("%ld %ld\n", found_max->first,found_max->second);

return 0;
}

Answer
std::map< T, T, std::greater<T> > store;

store has key sorted in descending order. Thus, [store.begin(), lower) contains (15, 22) and (10, 2). The element with maximum value is (15, 22).

Comments