1 /* C++ implementation of a binary search.
3 Copyright (C) 2019-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
21 #ifndef GDBSUPPORT_GDB_BINARY_SEARCH_H
22 #define GDBSUPPORT_GDB_BINARY_SEARCH_H
28 /* Implements a binary search using C++ iterators.
29 This differs from std::binary_search in that it returns an iterator for
30 the found element and in that the type of EL can be different from the
31 type of the elements in the container.
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
37 [first, last) must be sorted.
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
)
44 auto lt
= [&] (const typename
std::iterator_traits
<It
>::value_type
&a
,
46 { return comp (a
, b
) < 0; };
48 auto lb
= std::lower_bound (first
, last
, el
, lt
);
51 if (comp (*lb
, el
) == 0)
59 #endif /* GDBSUPPORT_GDB_BINARY_SEARCH_H */