upper_bound and lower_bound for non increasing vector in c++

The lower_bound() and upper_bound() functions by default work on non decreasing array. The lower_bound() function finds iterator of first element that does not compare less to given element. The upper_bound() function returns iterator to first element that is greater.

Given an array converting this to an non increasing vector, applying the std:: upper_bound and std:: lower_bound function to the vector

For array sorted in non-increasing array, lowe_bound() finds iterator to first element that does not compare greater than to given element. upper_bound() finds iterator to first element that is smaller than given element. We use grater() for this purpose.

 `// CPP program to demonstrate working of lower_bound() ` `// and upper_bound() for array sorted in non-decreasing ` `// array, ` `#include ` `#include ` `#include ` ` `  `int` `main() ` `{ ` `    ``int` `unsorted[10] = { 3, 3, 2, 1, 5, 5, 4, 3, 7, 8 }; ` `    ``std::vector<``int``> v(unsorted, unsorted + 10); ` ` `  `    ``// sorting vector in non increasing order. Vector ` `    ``// becomes {8, 7, 5, 5, 4, 3, 3, 3, 2, 1} ` `    ``std::sort(v.begin(), v.end(), std::greater<``int``>()); ` ` `  `    ``std::vector<``int``>::iterator low, up; ` `    ``low = std::lower_bound(v.begin(), v.end(), 3, std::greater<``int``>());          ` `    ``up = std::upper_bound(v.begin(), v.end(), 5, std::greater<``int``>());           ` ` `  `    ``std::cout << ``"lower_bound at position "` `<< (low - v.begin()) << ``'\n'``; ` `    ``std::cout << ``"upper_bound at position "` `<< (up - v.begin()) << ``'\n'``; ` ` `  `    ``return` `0; ` `} `

Output:

```lower_bound at position 5
upper_bound at position 4
```

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.