Atanu - 5 months ago 38

C++ Question

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

The

`lower_bound`

`std::max_element`

`begin()`

`lower_bound()`

But it's returning the last

`pair(15, 12)`

`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)`

.