gdb_binary_search.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* C++ implementation of a binary search.
  2. Copyright (C) 2019-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #ifndef GDBSUPPORT_GDB_BINARY_SEARCH_H
  15. #define GDBSUPPORT_GDB_BINARY_SEARCH_H
  16. #include <algorithm>
  17. namespace gdb {
  18. /* Implements a binary search using C++ iterators.
  19. This differs from std::binary_search in that it returns an iterator for
  20. the found element and in that the type of EL can be different from the
  21. type of the elements in the container.
  22. COMP is a C-style comparison function with signature:
  23. int comp(const value_type& a, const T& b);
  24. It should return -1, 0 or 1 if a is less than, equal to, or greater than
  25. b, respectively.
  26. [first, last) must be sorted.
  27. The return value is an iterator pointing to the found element, or LAST if
  28. no element was found. */
  29. template<typename It, typename T, typename Comp>
  30. It binary_search (It first, It last, T el, Comp comp)
  31. {
  32. auto lt = [&] (const typename std::iterator_traits<It>::value_type &a,
  33. const T &b)
  34. { return comp (a, b) < 0; };
  35. auto lb = std::lower_bound (first, last, el, lt);
  36. if (lb != last)
  37. {
  38. if (comp (*lb, el) == 0)
  39. return lb;
  40. }
  41. return last;
  42. }
  43. } /* namespace gdb */
  44. #endif /* GDBSUPPORT_GDB_BINARY_SEARCH_H */