In this chapter we shall learn about:
1. set introduction.
2. set declaration.
4. Passing std::set to function
5. set member function to iterate over elements.
6. set member function to check the capacity.
7. set member function to Modify the elements.
8. set member function to perform operations the elements.
1. set introduction.
Set are the container that stores unique 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.
Sets are typically implemented as binary search trees.
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. set declaration.
set<int> myset = {5, 4, 3, 2, 1, 1, 2};
4. Passing std::set to function
You can pass a set in 2 ways:
1. Pass by value
2. Pass by reference
1. Pass by value
void func(set<int> myset)
{
myset.insert(30);
}
int main()
{
set<int> myset = {5, 4, 3, 2, 1, 1, 2};
func(myset);
// as we are passing by value, the list will remain unchanged.
std::cout << "myset contains:"<<endl;
for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
return 0;
}
2. Pass by reference
void func(set<int> &myset)
{
myset.insert(30);
}
int main()
{
set<int> myset = {5, 4, 3, 2, 1, 1, 2};
func(myset);
// as we are passing by value, the list will remain unchanged.
std::cout << "myset contains:"<<endl;
for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
return 0;
}
Output:
myset contains:
1 2 3 4 5 30
5. set 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()
{
set<int> myset = {5, 4, 3, 2, 1, 1, 2};
std::cout << "myset contains using .begin():"<<endl;
for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::set<int>::reverse_iterator rit;
std::cout << "\nmyset contains using .rbegin:"<<endl;
for (rit=myset.rbegin(); rit != myset.rend(); ++rit)
std::cout << ' ' << *rit;
std::cout << "\nmyset contains using .cbegin:"<<endl;
for (auto it=myset.cbegin(); it != myset.cend(); ++it)
std::cout << ' ' << *it;
return 0;
}
myset contains using .begin():
1 2 3 4 5
myset contains using .rbegin:
5 4 3 2 1
myset contains using .cbegin:
1 2 3 4 5