C++ STL set, upper_bound() program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: How to use the C++ upper_bound() to return an iterator to the first element in a set with a key that is greater than a specified key in C++ programming
To show: Using the C++ set, upper_bound() to return an iterator to the first element in a set with a key that is greater than a specified key in C++ programming
// C++ STL set, upper_bound()
#include <set>
#include <iostream>
using namespace std;
int main(void)
{
// set container
set <int> st1;
// iterators
set <int> :: const_iterator st1Iter, st1PIter, st1QIter;
// insert data into st1 set
st1.insert(9);
st1.insert(12);
st1.insert(20);
st1.insert(13);
st1.insert(40);
// print the data
cout<<"st1 set data: ";
for(st1Iter = st1.begin(); st1Iter != st1.end(); st1Iter++)
cout<<" "<<*st1Iter;
cout<<endl;
st1QIter = st1.upper_bound(20);
cout<<"The first element of st1 set with a key greater than 20 is: "<<*st1QIter<<endl;
st1QIter = st1.upper_bound(11);
// if no match is found for the key, end( ) is returned
if(st1QIter == st1.end())
cout<<"The st1 set doesn't have an element with key greater than 40 is: "<<*st1QIter<<endl;
// the element at a specific location in the set can be found by using a dereferenced iterator addressing the location
st1PIter = st1.begin();
st1QIter = st1.upper_bound(*st1PIter);
cout<<"The first element of st1 set with a key greater than that of the initial element of st1 set is: "<<*st1QIter<<endl;
return 0;
}
Output examples:
st1 set data: 9 12 13 20 40
The first element of st1 set with a key greater than 20 is: 40
The first element of st1 set with a key greater than that of the initial element of st1 set is: 12
Press any key to continue . . .