</>

📜 lower_bound & upper_bound Guide 🚀


What it is: A pair of highly efficient binary search algorithms from the C++ <algorithm> library. They operate on any sorted range (like a sorted vector, a map, or a set) to find the position of elements.

Core Benefit: Guaranteed O(log N) time complexity for finding elements or insertion points in sorted sequences, which is vastly superior to a linear search.


✨ Essentials & Syntax

Operation Code Example Notes
Include #include <algorithm> Required for the global functions.
lower_bound auto it = std::lower_bound(vec.begin(), vec.end(), val); Finds iterator to the first element >= val.
upper_bound auto it = std::upper_bound(vec.begin(), vec.end(), val); Finds iterator to the first element > val.
Member Func. auto it = myMap.lower_bound(key); For map & set. More efficient than the global version.
Get Index auto idx = std::distance(vec.begin(), it); Converts an iterator to a zero-based index.
Check Found if (it != vec.end() && *it == val) { ... } How to check if lower_bound found an exact match.

🔄 Common Usage: Practical Examples

These functions are versatile for querying sorted data.


💡 Key Use Cases


🧠 Key Takeaways