MultiSet Container


The main difference between set and multiset is that in multiset we can use duplicate key values. In multiset containers, the member function equal_range( ) will have some use. Let’s see a program using multiset container.

#include <iostream>
#include <set>
using namespace std;

int main( )
{
typedef multiset<int,less<int> > intset;
intset intset1;
intset::const_iterator ptr;
pair<intset::const_iterator,intset::const_iterator> p;

intset1.insert(9);
intset1.insert(3);
intset1.insert(9);
intset1.insert(1);

for (int i=0;i<3;i++)
{
intset1.insert(8);
}

cout<<endl<<"The container has the following numbers:";
for (ptr=intset1.begin( );ptr!=intset1.end();ptr++)
{
cout<<" "<<*ptr;
}

cout<<endl<<"Size of the container: "<<intset1.size( );
p=intset1.equal_range(8);
cout<<endl<<"At the lower end:"<<*(p.first);
cout<<endl<<"At the upper end:"<<*(p.second);

return 0;
}

The output will be:

The container has the following numbers: 1 3 8 8 8 9 9

Size of the container: 7

At the lower end:8

At the upper end:9

The code:

pair<intset::const_iterator,intset::const_iterator> p;

will create an object ‘p’ of belonging to the class ‘pair’. Pair objects will contain a pair of values. The reason we have to use a pair in this program is because the equal_range( ) member function will return a pair of iterators. The function is:

pair-iterators equal_range(value)

The following diagram illustrates the iterators that are returned by equal_range(8).

 

 

 

Text Box: The second iterator
Text Box: The first iterator
Text Box: 9
Text Box: 9
Text Box: 8
Text Box: 8
Text Box: 8
Text Box: 3
Text Box: 1

 

To access the two iterators separately you can use the dot operator. The two parts are referred to as .first and .second. Hence in our program since the pair object is named ‘p’, we can refer to these two iterators as p.first and p.second.

Suppose you don’t want to get the pair of iterators and instead you just want one of them, you can use the member functions:

const_iterator lower_bound(value)

const_iterator upper_bound(value)

to yield the same results. The function lower_bound( ) returns an iterator pointing to the first occurrence of the ‘value’ element and upper_bound( ) returns an iterator past the last occurrence of the element with ‘value’.


Go to the next section on: Container Map

Go back to Contents page 2.


Copyright © 2004 Sethu Subramanian All rights reserved.