In this chapter we shall learn about:
1. multiset introduction.
2. multiset declaration.
4. Passing std::multiset to function
5. multiset member function to iterate over elements.
6. multiset member function to check the capacity.
7. multiset member function to Modify the elements.
8. multiset member function to perform operations the elements.
1. multiset introduction.
Multiset are similar to Set that stores duplicate elements.
These elements are stored in ascending or descending order.
The value of the elements in a set cannot be modified once in the container, they are always constant.
You can only insert or remove from the container.
In set the value of an element identifies it (the value is itself the key, of type T),
Below is the header file to be used for set:
#include <set>
2. multiset declaration.
multiset<int> mymultiset = {5, 4, 3, 2, 1, 1, 2};
4. Passing std::multiset to function
You can pass a multiset in 2 ways:
1. Pass by value
2. Pass by reference
1. Pass by value
void func(multiset<int> mymultiset)
{
mymultiset.insert(30);
}
int main()
{
multiset<int> mymultiset = {5, 4, 3, 2, 1, 1, 2};
func(mymultiset);
// as we are passing by value, the list will remain unchanged.
std::cout << "mymultiset contains:"<<endl;
for (std::multiset<int>::iterator it=mymultiset.begin(); it!=mymultiset.end(); ++it)
std::cout << ' ' << *it;
return 0;
}
2. Pass by reference
void func(multiset<int> &mymultiset)
{
mymultiset.insert(30);
}
int main()
{
multiset<int> mymultiset = {5, 4, 3, 2, 1, 1, 2};
func(mymultiset);
// as we are passing by value, the list will remain unchanged.
std::cout << "mymultiset contains:"<<endl;
for (std::multiset<int>::iterator it=mymultiset.begin(); it!=mymultiset.end(); ++it)
std::cout << ' ' << *it;
return 0;
}
Output:
mymultiset contains:
1 2 3 4 5 30
5. multiset member function to iterate over elements.
#include <iostream>
#include <set>
//for more tutorials on C, C++, STL, DS visit www.ProDeveloperTutorial.com
using namespace std;
int main()
{
multiset<int> mymultiset = {5, 4, 3, 2, 1, 1, 2};
std::cout << "mymultiset contains using .begin():"<<endl;
for (std::multiset<int>::iterator it=mymultiset.begin(); it!=mymultiset.end(); ++it)
std::cout << ' ' << *it;
std::multiset<int>::reverse_iterator rit;
std::cout << "\nmyset contains using .rbegin:"<<endl;
for (rit=mymultiset.rbegin(); rit != mymultiset.rend(); ++rit)
std::cout << ' ' << *rit;
std::cout << "\nmyset contains using .cbegin:"<<endl;
for (auto it=mymultiset.cbegin(); it != mymultiset.cend(); ++it)
std::cout << ' ' << *it;
return 0;
}
mymultiset contains using .begin():
1 1 2 2 3 4 5
myset contains using .rbegin:
5 4 3 2 2 1 1
myset contains using .cbegin:
1 1 2 2 3 4 5