C++: lower bound and upper bound of std::vector

lower bound and upper bound of a std::vector can be found by functions lower_bound and upper_bound.

The following code finds lower bound and upper bound of a std::vector data. The output should be

Raw data:
0 3 7 2 9 1 5 4 8 3 1 2
Sorted data:
0 1 1 2 2 3 3 4 5 7 8 9
Lower bound at position 5
Data greater than or equal to 3:
3 3 4 5 7 8 9
Upper bound at position 9
Data less than or equal to 5:
0 1 1 2 2 3 3 4 5


#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
    std::vector<int> data({0, 3, 7, 2, 9, 1, 5, 4, 8, 3, 1, 2});
    std::cout << "Raw data: " << std::endl << " ";
    for(int n = 0; n < data.size(); ++n)    std::cout << data[n] << "   ";
    std::cout << std::endl;

    std::sort(data.begin(), data.end());
    std::cout << "Sorted data: " << std::endl << " ";
    for(int n = 0; n < data.size(); ++n)    std::cout << data[n] << "   ";
    std::cout << std::endl;

    int thLb = 3;
    std::vector<int>::iterator lb = std::lower_bound(data.begin(), data.end(), thLb);
    int posLb = (int)(lb - data.begin());
    std::cout << "Lower bound at position " << posLb << std::endl;
    std::cout << "Data greater than or equal to " << thLb << ": " << std::endl << " ";
    for(int n = posLb; n < data.size(); ++n)    std::cout << data[n] << "   ";
    std::cout << std::endl;

    int thUb = 5;
    std::vector<int>::iterator ub = std::upper_bound(data.begin(), data.end(), 5);
    int posUb = (int)(ub - data.begin());
    std::cout << "Upper bound at position " << posUb << std::endl;
    std::cout << "Data less than or equal to " << thUb << ": " << std::endl << "    ";
    for(int n = 0; n < posUb; ++n)    std::cout << data[n] << "   ";
    std::cout << std::endl;

    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s