Browse Source

Add LowerBound and UpperBound functions.

Eugene Kozlov 9 years ago
parent
commit
583c851b03
1 changed files with 46 additions and 0 deletions
  1. 46 0
      Source/Urho3D/Container/VectorBase.h

+ 46 - 0
Source/Urho3D/Container/VectorBase.h

@@ -238,6 +238,52 @@ template <class T> struct RandomAccessConstIterator
     T* ptr_;
 };
 
+/// Returns an iterator pointing to the first element in the range [first, last) that is not less than value.
+template <class TRandomAccessIterator, class T>
+TRandomAccessIterator LowerBound(TRandomAccessIterator first, TRandomAccessIterator last, const T& value)
+{
+    unsigned count = last - first;
+
+    while (count > 0)
+    {
+        const unsigned step = count / 2;
+        const TRandomAccessIterator it = first + step;
+        if (*it < value)
+        {
+            first = it + 1;
+            count -= step + 1;
+        }
+        else
+        {
+            count = step;
+        }
+    }
+    return first;
+}
+
+/// Returns an iterator pointing to the first element in the range [first, last) that is greater than value.
+template <class TRandomAccessIterator, class T>
+TRandomAccessIterator UpperBound(TRandomAccessIterator first, TRandomAccessIterator last, const T& value)
+{
+    unsigned count = last - first;
+
+    while (count > 0)
+    {
+        const unsigned step = count / 2;
+        const TRandomAccessIterator it = first + step;
+        if (!(value < *it))
+        {
+            first = it + 1;
+            count -= step + 1;
+        }
+        else
+        {
+            count = step;
+        };
+    }
+    return first;
+}
+
 /// %Vector base class.
 /** Note that to prevent extra memory use due to vtable pointer, %VectorBase intentionally does not declare a virtual destructor
     and therefore %VectorBase pointers should never be used.