Use std::bsearch in LookupByKey for binary search
This commit is contained in:
parent
f64e040896
commit
c8f1682e07
|
@ -305,36 +305,36 @@ public:
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename K> return_type LookupByKey(K key) const {
|
template<typename K> return_type LookupByKey(K key) const {
|
||||||
auto span = size();
|
std::size_t count = size();
|
||||||
uoffset_t start = 0;
|
void *search_result = std::bsearch(&key, Data(), count,
|
||||||
// Perform binary search for key.
|
IndirectHelper<T>::element_stride, KeyCompare<K>);
|
||||||
while (span) {
|
|
||||||
// Compare against middle element of current span.
|
if (!search_result) {
|
||||||
auto middle = span / 2;
|
|
||||||
auto table = Get(start + middle);
|
|
||||||
auto comp = table->KeyCompareWithValue(key);
|
|
||||||
if (comp > 0) {
|
|
||||||
// Greater than. Adjust span and try again.
|
|
||||||
span = middle;
|
|
||||||
} else if (comp < 0) {
|
|
||||||
// Less than. Adjust span and try again.
|
|
||||||
middle++;
|
|
||||||
start += middle;
|
|
||||||
span -= middle;
|
|
||||||
} else {
|
|
||||||
// Found element.
|
|
||||||
return table;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nullptr; // Key not found.
|
return nullptr; // Key not found.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const uint8_t *data = reinterpret_cast<const uint8_t *>(search_result);
|
||||||
|
|
||||||
|
return IndirectHelper<T>::Read(data, 0);
|
||||||
|
}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
// This class is only used to access pre-existing data. Don't ever
|
// This class is only used to access pre-existing data. Don't ever
|
||||||
// try to construct these manually.
|
// try to construct these manually.
|
||||||
Vector();
|
Vector();
|
||||||
|
|
||||||
uoffset_t length_;
|
uoffset_t length_;
|
||||||
|
|
||||||
|
private:
|
||||||
|
template<typename K> static int KeyCompare(const void *ap, const void *bp) {
|
||||||
|
const K *key = reinterpret_cast<const K *>(ap);
|
||||||
|
const uint8_t *data = reinterpret_cast<const uint8_t *>(bp);
|
||||||
|
auto table = IndirectHelper<T>::Read(data, 0);
|
||||||
|
|
||||||
|
// std::bsearch compares with the operands transposed, so we negate the
|
||||||
|
// result here.
|
||||||
|
return -table->KeyCompareWithValue(*key);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Convenient helper function to get the length of any vector, regardless
|
// Convenient helper function to get the length of any vector, regardless
|
||||||
|
|
Loading…
Reference in New Issue