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