In this tutorial, we are going to explore the variances between the std::lowerbound and std::set::lowerbound function in C++. Prior to delving into their distinctions, it is essential to understand the functionality of both the std::lowerbound and std::set::lowerbound function.
What is std::lower_bound in C++?
The std::lowerbound function identifies the initial position within a sorted range where inserting a specific value would maintain the sorting order, accomplished through a binary search algorithm. It returns an iterator pointing to the first element in the range [first, last] that is greater than or equal to the provided value. In simpler terms, std::lowerbound locates the index of the smallest element in the sorted range that is equal to or larger than the input value. All elements preceding this iterator are guaranteed to be smaller than the value. As for the elements following the position returned by std::lowerbound, they may or may not be greater than or equal to the value. This functionality of std::lowerbound is particularly useful for optimizing searches and insertions within organized data structures.
What is std::set::lower_bound in C++?
The lower_bound function in std::set performs a binary search to determine the appropriate position for inserting a specific key while maintaining the set's order. It provides an iterator pointing to the first element that is equal to or greater than the sought-after key.
If the specified key is absent within the Set, the lower_bound function provides an iterator to the subsequent element with a higher sorting order than the sought key. This feature identifies the lowest possible position for the key within the Ordered Set. Such functionality enhances the Set's search efficiency, particularly for keys that are not currently part of the Set.
The lower_bound function will return an iterator pointing to the position just after the last element in the set if the specified key is greater than the highest element in the set container.
What is the difference between std::lower_bound and set::lower_bound?
The subsequent table contrasts std::lowerbound with std::set::lowerbound in a structured manner.
| Feature | std::lower_bound | std::set::lower_bound |
|---|---|---|
| Defined in | _PRESERVE4__ header | Set class definition |
| Inputs | - Iterator range_PRESERVE5__- Value to search for | - Key to search for |
| Returns | Iterator pointing to the first element not less than thevalue. | Iterator pointing to the first element not less than thekey. |
| Container Type | It works on anysortedcontainer/range e.g. vector, array. | It is specifically forstd::setcontainers. |
| Time Complexity | O(log n) | O(log n) |
| Key Comparisons | Uses user-provided comparison e.g.<, == | Uses std::set's comparator |
| Insertion Position | Returns insertion point to maintain ordering. | Returns insertion point to maintain set ordering. |
| Common Usage | General binary search on sorted data | Lookup/insertion into a sortedstd::set |
| Flexibility | It works withcustom data typesvia custom comparators. | It only works with data types that support<operator. |
| Iterators | Returns regular iterator into range | Returns iterator aware of set's tree structure |
| Performance | Binary search algorithm | Leverages tree structure, may have faster constants |
| Use Cases | Commonly used with vectors, arrays | Useful when data needs ordering and uniqueness |
| Implementation | Binary search algorithm | Utilizes set's underlying tree structure |
| Element Uniqueness | Does not guarantee uniqueness | Elements are unique in set |
| Container Requirements | Any sorted range | Restricted to set containers |
| Custom Sorting | Custom comparator can define sort order | Fixed sorting based on < operator |
| Insertion Rules | Insertion keeps sorted order | Insertion maintains set ordering rules |
while std::set::lower_bound is a set member function that utilizes its ordering specifically for lookup/insertion in a set. But both return the "lower boundary" for a value in O(log n) time.
Example:
Let's consider a program to demonstrate the utilization of std::lower_bound in C++:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Create a sorted vector of integers
std::vector<int> vec = {1, 2, 4, 4, 5, 7, 8, 10};
// Value to search for
int target = 6;
// Use std::lower_bound to find the position of the first element not less than target
auto it = std::lower_bound(vec.begin(), vec.end(), target);
// Output the result
std::cout << "Vector contains: ";
for (int num : vec) {
std::cout << num << " ";
}
if (it != vec.end()) {
std::cout << "\nFirst element not less than " << target << " is at position: " << std::distance(vec.begin(), it);
} else {
std::cout << "\nNo element not less than " << target << " found in the vector.";
}
return 0;
}
Output:
Vector contains: 1 2 4 4 5 7 8 10
First element not less than 6 is at position: 5
In this instance, the desired value is 35, and the std::lower_bound function is employed to determine the index where 35 could be added into the vector to uphold its sorted sequence. The result specifies that the insertion of element 35 at index 3 would preserve the sorted order.
Explanation:
- The program creates a sorted vector of integers.
- It defines a target value to search for (in this case, target = 6).
- It uses std::lower_bound to find the iterator pointing to the first element not less than the target.
- After that, the program outputs the original vector and the position of the first element, which is not less than the target.
Example:
Let's consider a program to demonstrate the application of std::set::lower_bound in the C++ programming language:
#include <iostream>
#include <set>
int main() {
// Create a set of integers
std::set<int> mySet = {1, 2, 4, 5, 7, 8, 10};
// Value to search for
int target = 6;
// Use std::set::lower_bound to find the iterator pointing to the first element not less than target
auto it = mySet.lower_bound(target);
// Output the result
std::cout << "Set contains: ";
for (int num : mySet) {
std::cout << num << " ";
}
if (it != mySet.end()) {
std::cout << "\nFirst element not less than " << target << " is: " << *it;
} else {
std::cout << "\nNo element not less than " << target << " found in the set.";
}
return 0;
}
Output:
Set contains: 1 2 4 5 7 8 10
First element not less than 6 is: 7
In this instance, the std::set::lower_bound method is employed to determine the appropriate position to insert 35 in the Set for preserving the sorted sequence. The result suggests that the element 35 could be added at index 4 to uphold the ordered arrangement. When the element is not located, the function provides an iterator pointing to the initial element that is greater than the specified target.
Explanation:
- The program creates a set of integers. The set is always sorted by default.
- It defines a target value to search for (in this case, target = 6).
- It uses std::set::lower_bound to find the iterator pointing to the first element that is not less than the target.
- After that, the program outputs the original set and the first element, which is not less than the target.
Conclusion:
The std::lowerbound function is a versatile algorithm designed to execute a binary search for determining the position where a key should be inserted within any sorted container. In contrast, std::set::lowerbound is a member function specific to std::set that capitalizes on the inherent ordering of sets to swiftly pinpoint the position of a key or the subsequent element with higher significance in logarithmic time. While the former is suitable for sorted ranges in general, the latter is tailored for optimal performance with std::set containers.