c++ set code example
Example 1: set and get in c++
class Employee {
private:
int salary;
public:
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Example 2: set in c++
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
void setDemo()
{
set<int> S;
S.insert(1);
S.insert(2);
S.insert(-1);
S.insert(-10);
S.erase(1);
for(int x:S){
cout<<x<<" ";
}
auto it = S.find(-1);
if (it == S.end()){
cout<<"not Present\n";
}else{
cout <<" present\n";
cout << *it <<endl;
}
auto it2 = S.lower_bound(-1);
auto it3 = S.upper_bound(-1);
cout<<*it2<<" "<<*it3<<endl;
}
int main() {
setDemo();
return 0;
}
Example 3: set in cpp
#include<iostream>
#include<set>
using namespace std;
int main(){
set<int, greater<int>> s1 = {6, 10, 5, 1};
s1.insert(12);
s1.insert(20);
s1.insert(3);
set<int> :: iterator it;
for(it=s1.begin(); it != s1.end();it++)
cout<<*it<<" ";
cout<<endl;
}
Example 4: set in cpp
#include<iostream>
#include<set>
using namespace std;
int main(){
set<int, greater<int>> s1 = {6, 10, 5, 1};
set<int> :: iterator it;
for(it=s1.begin(); it != s1.end();it++)
cout<<*it<<" ";
cout<<endl;
}
Example 5: sets in c++
set<int>s;
Example 6: set c++
#include <iostream>
#include <set>
bool fncomp (int lhs, int rhs) {return lhs<rhs;}
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs<rhs;}
};
int main ()
{
std::set<int> first;
int myints[]= {10,20,30,40,50};
std::set<int> second (myints,myints+5);
std::set<int> third (second);
std::set<int> fourth (second.begin(), second.end());
std::set<int,classcomp> fifth;
bool(*fn_pt)(int,int) = fncomp;
std::set<int,bool(*)(int,int)> sixth (fn_pt);
return 0;
}