Search code examples
c++treestlsetbinary-search

Lower bound in Set STL in c++


I understand that set is implemented as tree structure internally in c++ . So, how does lower_bound gets performed on it? I mean I understand for vector that you pick the middle element using the start and end indexes and perform binary search, but how does it get implemented for tree like structures?


Solution

  • Finding the lower_bound in a set is almost the same as searching for an element in the set. At the end of the search (navigating the tree) you've either found the node where the element is, or you find an element that is greater than the one you're looking for, but there aren't any nodes with a lower value in its subtree (so this is where you'd want to insert the value if you were adding it, as the left child of this node).

    Either way you've found the lower bound for the element.