C++ STL set, lower_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: Using the C++ lower_bound() to return an iterator to the first element in a set with a key that is equal to or greater than a specified key in C++ programming
To show: How to use the C++ set, lower_bound() to return an iterator to the first element in a set with a key that is equal to or greater than a specified key in C++ programming
// C++ STL set, lower_bound()
#include <set>
#include <iostream>
using namespace std;
int main(void)
{
// container
set <int> st1;
// iterators
set <int> :: const_iterator st1Iter, st1_PIter, st1_QIter;
// push/insert data
st1.insert(11);
st1.insert(21);
st1.insert(30);
st1.insert(10);
st1.insert(22);
// print the data and do other operations
cout<<"st1 set data: ";
for(st1Iter = st1.begin(); st1Iter != st1.end(); st1Iter++)
cout<<" "<<*st1Iter;
cout<<endl;
st1_QIter = st1.lower_bound(21);
cout<<"The element of st1 set with a key of 21 is: "<<*st1_QIter<<endl;
st1_QIter = st1.lower_bound(60);
// if no match is found for the key, end() is returned
if(st1_QIter == st1.end())
cout<<"The st1 set doesn't have an element with a key of 60"<<endl;
else
cout<<"The element of set st1 with a key of 60 is: "<<*st1_QIter<<endl;
// the element at a specific location in the set can be found by using a dereferenced iterator that addresses the location
st1_PIter = st1.end();
st1_PIter--;
st1_QIter = st1.lower_bound(*st1_PIter);
cout<<"The element of st1 with a key matching that of the last element is: "<<*st1_QIter<<endl;
return 0;
}
Output examples:
st1 set data: 10 11 21 22 30
The element of st1 set with a key of 21 is: 21
The st1 set doesn't have an element with a key of 60
The element of st1 with a key matching that of the last element is: 30
Press any key to continue . . .