I have in memory an array of 16 byte wide entries. Each entry consists of two 64 bit integer fields. The entries are in sorted order based upon the numerical value of the first 64 bit integer of each entry. Is it possible to binary search this with the STL without first loading the data into a std::vector?
I have seen that I can use the STL lower_bound() method on plain arrays, but I need it to ignore the second 64 bit field of eachy entry. Is this possible?
But in Array of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose the first value is greater than or equals x and second value is greater than equals to y.
C++ Algorithm lower_bound() function is the version of binary search. This function is used to return an iterator pointing to the first element in an ordered range [first, last) that is not less than (i.e. greater than or equal to) to the specified value val.
set::lower_bound() function in C++ STL In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k.
The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than val. This means that the function returns an iterator pointing to the next smallest number just greater than or equal to that number.
You don't need to use std::vector<>
, but it is easiest if you get your data into a proper data type first:
#include <cstdint>
struct mystruct
{
std::int64_t first, second;
};
Your question is unclear as to the way you're storing this data now, but I'm assuming it's something like the above.
Then you can either overload operator<
for your data type:
#include <algorithm>
bool operator <(mystruct const& ms, std::int64_t const i)
{
return ms.first < i;
}
int main()
{
mystruct mss[10] = { /*populate somehow*/ };
std::int64_t search_for = /*value*/;
mystruct* found = std::lower_bound(mss, mss + 10, search_for);
}
Or you can define a custom comparator and pass that to std::lower_bound
:
#include <algorithm>
struct mystruct_comparer
{
bool operator ()(mystruct const& ms, std::int64_t const i) const
{
return ms.first < i;
}
};
int main()
{
mystruct mss[10] = { /*populate somehow*/ };
std::int64_t search_for = /*value*/;
mystruct* found = std::lower_bound(mss,
mss + 10,
search_for,
mystruct_comparer());
}
Naturally, in C++11, a lambda can be used instead of a full-fledged functor for the comparator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With