I am new in C++ world. There is a upper_bound function in a set that returns number greater than passed value. I would like to know if there is any way to get a number lower than the passed value? Let's say if we have {3,6,8,9,11} in set and by passing to my function: func(8), I will receive 6, since 6 is the number that stays before 8. Any idea?
            Asked
            
        
        
            Active
            
        
            Viewed 204 times
        
    1
            
            
        - 
                    `std::upper_bound` (as well as `std::lower_bound`, which is more suitable here) returns an _iterator_. If this is _bidirectional_, you can iterate back to find your desired number. – Daniel Langr Jan 24 '22 at 14:26
1 Answers
3
            
            
        Your approach is reasonable, but instead of std::upper_bound, you should use std::lower_bound, like this for example:
#include <iostream>
#include <set>
using namespace std;
int main(void)
{
    set<int> myset{3, 6, 8, 9, 11};
    set<int>::iterator it = myset.lower_bound(8);
    if (it != myset.begin()) {
        it--;
        cout << *it << endl;
    } else {
        cout << "No smaller element found!" << endl;
    }
  return 0;
}
Ouptut:
6
 
    
    
        gsamaras
        
- 71,951
- 46
- 188
- 305
- 
                    2
- 
                    Oh, intermixed `using namespace std` and `std` namespace declarations... I'd prefer [dropping the former](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Aconcagua Jan 24 '22 at 14:43
- 
                    @appleapple and Aconcagua good catch! Those were leftovers, which I've now removed! Although I agree with the link, IMHO `using namespace std;` in such small and compact examples allows the reader to focus on what matters. – gsamaras Jan 24 '22 at 14:55
