Make BinarySearch() interface slightly more readable

Replace "equal" parameter with the (opposite) "lowerBound" one with a
more descriptive name, add a comment describing it and also remove the
default value to force explaining how it is used in the caller.

No real changes.
This commit is contained in:
Vadim Zeitlin
2021-02-26 16:25:28 +01:00
parent 00fec01308
commit 6819b5512b
2 changed files with 8 additions and 6 deletions

View File

@@ -398,8 +398,10 @@ private:
// (if the old buffer is big enough, just return NULL). // (if the old buffer is big enough, just return NULL).
wxString *Grow(size_t nIncrement); wxString *Grow(size_t nIncrement);
// Binary search in the sorted array // Binary search in the sorted array: return the index of the string if it's
size_t BinarySearch(const wxString& str, bool equal = false) const; // present, otherwise, if lowerBound is true, return the position at which
// the string should be inserted and if it's false return wxNOT_FOUND.
size_t BinarySearch(const wxString& str, bool lowerBound) const;
size_t m_nSize, // current size of the array size_t m_nSize, // current size of the array
m_nCount; // current number of elements m_nCount; // current number of elements

View File

@@ -379,7 +379,7 @@ void wxArrayString::Shrink()
} }
// Binary search in the sorted array // Binary search in the sorted array
size_t wxArrayString::BinarySearch(const wxString& str, bool equal) const size_t wxArrayString::BinarySearch(const wxString& str, bool lowerBound) const
{ {
size_t size_t
lo = 0, lo = 0,
@@ -398,7 +398,7 @@ size_t wxArrayString::BinarySearch(const wxString& str, bool equal) const
return i; return i;
} }
wxASSERT_MSG(lo == hi, wxT("binary search broken")); wxASSERT_MSG(lo == hi, wxT("binary search broken"));
return equal ? wxNOT_FOUND : lo; return lowerBound ? lo : wxNOT_FOUND;
} }
// searches the array for an item (forward or backwards) // searches the array for an item (forward or backwards)
@@ -408,7 +408,7 @@ int wxArrayString::Index(const wxString& str, bool bCase, bool bFromEnd) const
// use binary search in the sorted array // use binary search in the sorted array
wxASSERT_MSG( bCase && !bFromEnd, wxASSERT_MSG( bCase && !bFromEnd,
wxT("search parameters ignored for auto sorted array") ); wxT("search parameters ignored for auto sorted array") );
return BinarySearch(str, true); return BinarySearch(str, false /* not lower bound */);
} }
else { else {
// use linear search in unsorted array // use linear search in unsorted array
@@ -438,7 +438,7 @@ size_t wxArrayString::Add(const wxString& str, size_t nInsert)
{ {
if ( m_autoSort ) { if ( m_autoSort ) {
// insert the string at the correct position to keep the array sorted // insert the string at the correct position to keep the array sorted
size_t nIndex = BinarySearch(str); size_t nIndex = BinarySearch(str, true /* return lower bound */);
Insert(str, nIndex, nInsert); Insert(str, nIndex, nInsert);
return nIndex; return nIndex;
} }