Advertisement
Alaricy

поиск сортированый пизжено

Dec 27th, 2022
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. #include <set>
  5.  
  6. using namespace std;
  7.  
  8. set<int>::const_iterator FindNearestElement(const set<int>& numbers, int border) {
  9.     // set<int>::const_iterator — тип итераторов для константного множества целых чисел
  10.     if (numbers.empty()){return numbers.end();}
  11.     if (border <= *numbers.begin()){return numbers.begin();}
  12.     if (border >= *prev(numbers.end(), 1)){return prev(numbers.end());}
  13.     auto it = numbers.lower_bound(border);
  14.     if (border == *it){return it;}
  15.     if (border - *prev(it, 1) <= *it - border){
  16.         return prev(it, 1);
  17.     }
  18.     return it;
  19. }
  20.  
  21. int main() {
  22.     set<int> numbers = {1, 4, 6};
  23.     cout << *FindNearestElement(numbers, 0) << " " << *FindNearestElement(numbers, 3) << " "
  24.          << *FindNearestElement(numbers, 5) << " " << *FindNearestElement(numbers, 6) << " "
  25.          << *FindNearestElement(numbers, 100) << endl;
  26.     set<int> empty_set;
  27.     cout << (FindNearestElement(empty_set, 8) == end(empty_set)) << endl;
  28.     return 0;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement