Advertisement
Alaricy

поиск ближайшего

Dec 27th, 2022
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. //#include <vector>
  4. #include <set>
  5. //#include <cmath>
  6.  
  7. using namespace std;
  8.  
  9. set<int>::const_iterator FindNearestElement(const set<int>& numbers, int border)
  10. {
  11. auto it1 = lower_bound(numbers.begin(), numbers.end(), border);
  12. auto it2 = it1;
  13. if (*it1==border) return it1;
  14. if (it1!=numbers.begin())
  15. {
  16.     --it2;
  17.     if  (abs(-*it2+border)<=abs(-*it1+border)) return it2;
  18. } /*else*/ return it1;
  19. }
  20.  
  21. int main()
  22. {
  23.     setlocale(LC_ALL, "RU");
  24.     set<int> numbers = { 1, 4, 6};
  25.     cout << *FindNearestElement(numbers, 0) << " " << *FindNearestElement(numbers, 3) << " "
  26.         << *FindNearestElement(numbers, 5) << " " << *FindNearestElement(numbers, 6) << " "
  27.         << *FindNearestElement(numbers, 100) << endl;
  28.     set<int> empty_set;
  29.     cout << (FindNearestElement(empty_set, 8) == end(empty_set)) << endl;
  30.  
  31.     return 0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement