In: Computer Science
What are some tips and best practices on how to use sets and maps properly in C++? Please provide two examples.
Sets and Maps are both used to store unique as well as sorted values. So if you want to use them properly, first you need to learn about their differences and how and when to use them.
Differences:-
Uses:-
We use sets when we only want to display the sorted values. But when we need to print their frequency of the values, then we use the maps concept here.
Below are two examples for sets and maps.
Source Code:-
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> S;
S.insert(10);
S.insert(5);
S.insert(1);
S.insert(20);
cout<< "Values in Set : ";
for(auto s : S) {
cout << s << " ";
}
return 0;
}
Output :-
Values in Set : 1 5 10 20
Source Code:-
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
std::map<int, int> M;
M[10] = 1010;
M[5] = 101;
M.insert({4, 100});
cout << "Values in Map : ";
for(auto m : M) {
cout<< m.first << " " << m.second <<
"\n";
}
return 0;
}
Output:-
Values in Map : 4 100
5 101
10 1010
Hope this helps you!!