c++ - How to optimize binary search of a vector? -
i trying implement find method on sorted vector of key value pairs. right performing slower map.find(key). theoretically should faster because vector can take better advantage of cpu caching because of contiguous memory. i'm wondering if there wrong implementation , if there way can optimize it? don't think using standard algorithm option here, because closest possible option lower_bound , incur overhead of checks have perform verify whether or not found anything. beyond that, lower_bound require me construct pair (plus wrapper put around it) give value i'm searching for, incurring more unnecessary overhead. flatmap<key, value, comparator>::findimp(const key_type &key) { typename vectortype::iterator lower = d_elements.begin(); typename vectortype::iterator upper = d_elements.end(); typename vectortype::iterator middle; while(lower < upper) { middle = lower + (upper-lower)/2; if(d_comparator(middle->data().first, key)){ ...