C++ STL set, equal_range() code 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++ equal_range() to return a pair of iterators respectively to the first element in a set with a key that is greater than a specified key and to the first element in the set with a key that is equal to or greater than the key in C++ programming

To show: How to use the C++ set, equal_range() to return a pair of iterators respectively to the first element in a set with a key that is greater than a specified key and to the first element in the set with a key that is equal to or greater than the key in C++ programming

 

// C++ STL set, equal_range()

#include <set>

#include <iostream>

using namespace std;

 

int main(void)

{

// simplify set<int, less<int> > to IntSet

typedef set<int, less<int> > IntSet;

IntSet st1;

// iterators

set <int>::iterator st1Iter;

set <int, less<int> > :: const_iterator st1_RcIter;

 

// insert/push data

st1.insert(10);

st1.insert(20);

st1.insert(30);

st1.insert(40);

st1.insert(50);

 

// print the data and do other operations

cout<<"st1 set data: ";

for(st1Iter = st1.begin(); st1Iter != st1.end(); st1Iter++)

cout<<" "<<*st1Iter;

cout<<endl;

pair <IntSet::const_iterator, IntSet::const_iterator> p1, p2;

p1 = st1.equal_range(30);

cout<<"\nThe upper bound of the element with a key of 30 in the st1 set is: "<<*(p1.second)<<endl;

cout<<"\nThe lower bound of the element with a key of 30 in the st1 set is: "<<*(p1.first)<<endl;

// compare the upper_bound() called directly

st1_RcIter = st1.upper_bound(30);

cout<<"\nA direct call of upper_bound(30) gives "<<*st1_RcIter<<" matching the 2nd element of the pair"

<<" returned by equal_range(30)"<<endl;

cout<<"\nOperation: p2 = st1.equal_range(60)"<<endl;

p2 = st1.equal_range(60);

// If no match is found for the key, both elements of the pair return end()

if ((p2.first == st1.end()) && (p2.second == st1.end()))

cout<<"\nThe st1 set doesn't have an element with >= 60 is: "<<*(p1.first)<<endl;

return 0;

}

 

Output examples:

 

st1 set data: 10 20 30 40 50

The upper bound of the element with a key of 30 in the st1 set is: 40

The lower bound of the element with a key of 30 in the st1 set is: 30

A direct call of upper_bound(30) gives 40 matching the 2nd element of the pair returned by equal_range(30)

Operation: p2 = st1.equal_range(60)

The st1 set doesn't have an element with >= 60 is: 30

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index