C++ STL multiset, find() 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++ find() to return an iterator addressing the first location of an element in a multiset that has a key equivalent to a specified key in C++ programming

To show: How to use the C++ multiset, find() to return an iterator addressing the first location of an element in a multiset that has a key equivalent to a specified key in C++ programming

 

// C++ STL multiset, find()

#include <set>

#include <iostream>

using namespace std;

 

int main(void)

{

// container

multiset <int> mst1;

// iterators

multiset <int>::const_iterator mst1_QIter, mst1_PIter, mst1_RIter;

 

// inserting/pushing data into multiset

mst1.insert(6);

mst1.insert(2);

mst1.insert(14);

mst1.insert(6);

mst1.insert(10);

 

// print the data and do some operations

cout<<"mst1 multiset data: ";

for(mst1_RIter = mst1.begin(); mst1_RIter != mst1.end(); mst1_RIter++)

cout<<" "<<*mst1_RIter;

cout<<endl;

mst1_PIter = mst1.find(10);

cout<<"The first element of multiset mst1 with a key of 10 is: "<<*mst1_PIter<<endl;

mst1_PIter = mst1.find(21);

// If no match is found for the key, end() is returned

if(mst1_PIter == mst1.end())

cout<<"\nThe mst1 multiset doesn't have an element with a key of 21"<<endl;

else

cout<<"\nThe element of mst1 multiset with a key of 21 is: "<<*mst1_PIter<<endl;

// the element at a specific location in the multiset can be found using a dereferenced iterator addressing the location

mst1_QIter = mst1.end();

mst1_QIter--;

mst1_PIter = mst1.find(*mst1_QIter);

cout<<"\nThe first element of mst1 multiset with a key matching that of the last element is: "<<*mst1_PIter<<endl;

// note that the first element with a key equal to the key of the last element is not the last element

if(mst1_PIter == --mst1.end())

cout<<"\nThis is the last element of mst1 multiset"<<endl;

else

cout<<"\nThis is not the last element of mst1 multiset"<<endl;

return 0;

}

 

Output examples:

 

mst1 multiset data: 2 6 6 10 14

The first element of multiset mst1 with a key of 10 is: 10

The mst1 multiset doesn't have an element with a key of 21

The first element of mst1 multiset with a key matching that of the last element is: 14

This is the last element of mst1 multiset

Press any key to continue . . .

 

 

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