c++ - Is it possible to use lower_bound() to binary search a plain array of structs? -


i have in memory array of 16 byte wide entries. each entry consists of 2 64 bit integer fields. entries in sorted order based upon numerical value of first 64 bit integer of each entry. possible binary search stl without first loading data std::vector?

i have seen can use stl lower_bound() method on plain arrays, need ignore second 64 bit field of eachy entry. possible?

you don't need use std::vector<>, easiest if data proper data type first:

#include <cstdint> struct mystruct { std::int64_t first, second; }; 

your question unclear way you're storing data now, i'm assuming it's above.

then can either overload operator< 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 can define custom comparator , pass 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, lambda can used instead of full-fledged functor comparator.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -