Introduction to Efficient Queries Using C++ STL Sets

Greetings, aspiring coders! Today, we're going to delve deep into the complexities of data structures, specifically the std::set from the C++ Standard Template Library (STL), and explore how to handle queries efficiently. This is a common problem, often encountered in numerous data science and algorithmic problems. So let's gear up to unravel the mysteries of std::set operations and get our hands dirty with some interactive problem-solving!

std::set Operations and Time Complexity

Before delving into the task, let's understand what a std::set is and why we would use it. std::set is a data structure in the C++ STL that stores unique elements while maintaining sorted order.

Advantages of using std::set:

  1. Extracting minimum (using *set.begin()) or maximum (using *(--set.end())) values will be a constant time operation, i.e., O(1)O(1) as they are always at the start or end of the set.
  2. Achieving sorted order after every insertion or deletion happens automatically with std::set, and the operations have a logarithmic time complexity O(logN)O(\log N).

Understanding these operations can help us utilize std::set efficiently for our problem.

The `std::lower_bound` and `std::upper_bound` Functions

The std::set data structure includes useful functions called std::lower_bound and std::upper_bound.

The std::lower_bound function finds the first element in a sorted range that is not less than a given value. If the element already exists in the set, the iterator points to the element itself.

For example: If we have a std::set as {1, 2, 4, 6, 8}, set.lower_bound(4) will return an iterator pointing to 4, as 4 exists in the set.

Similarly, the std::upper_bound function finds the first element in a sorted range that is greater than a given value.

Here is an example of how you would use std::lower_bound and std::upper_bound on a std::set:

#include <iostream>
#include <set>

int main() {
    std::set<int> sorted_set = {1, 2, 4, 6, 8};
    auto it1 = sorted_set.lower_bound(4);
    auto it2 = sorted_set.upper_bound(4);

    std::cout << *it1 << " " << (it2 != sorted_set.end() ? std::to_string(*it2) : "end") << std::endl;  // Output: 4 6
    return 0;
}
Task Statement
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal