Open In App

Implementation of lower_bound() and upper_bound() in Vector of Pairs in C++

Here we will discuss the implementation of the lower_bound() and upper_bound() in vector of pairs

lower_bound():

 It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equal to the given value “val”. But in Vector of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the position of pair whose  



If the above-mentioned criteria are not met, then it returns an iterator to the index which is out of the vectors of pairs. 

upper_bound():

It returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in Vector of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the position of the pair whose



Below is the program to demonstrate lower_bound() and upper_bound() in vector of pairs:

Program 1:  




// C++ program to demonstrate lower_bound()
// and upper_bound() in Vectors of Pairs
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to implement lower_bound()
void findLowerBound(vector<pair<int, int> >& arr,
                    pair<int, int>& p)
{
    // Given iterator points to the
    // lower_bound() of given pair
    auto low = lower_bound(arr.begin(), arr.end(), p);
 
    cout << "lower_bound() for {2, 5}"
         << " is at index: " << low - arr.begin() << endl;
}
 
// Function to implement upper_bound()
void findUpperBound(vector<pair<int, int> >& arr,
                    pair<int, int>& p)
{
    // Given iterator points to the
    // upper_bound() of given pair
    auto up = upper_bound(arr.begin(), arr.end(), p);
 
    cout << "upper_bound() for {2, 5}"
         << " is at index: " << up - arr.begin() << endl;
}
 
// Driver Code
int main()
{
    // Given sorted vector of Pairs
    vector<pair<int, int> > arr;
    arr = { { 1, 3 }, { 1, 7 }, { 2, 4 },
            { 2, 5 }, { 3, 8 }, { 8, 6 } };
 
    // Given pair {2, 5}
    pair<int, int> p = { 2, 5 };
 
    // Function Call to find lower_bound
    // of pair p in arr
    findLowerBound(arr, p);
 
    // Function Call to find upper_bound
    // of pair p in arr
    findUpperBound(arr, p);
 
    return 0;
}

Output
lower_bound() for {2, 5} is at index: 3
upper_bound() for {2, 5} is at index: 4

Article Tags :
C++