Introduction:
Keys(left) and values(right) can be inserted into a Map. Keys are unique while values can be duplicated. Map sorts keys in ascending order by default. Keys and values can be any type of data type like int, string, set, pair and so on.
Lets have a look at the code snippet below:
Basic Code 1:
#include<iostream>
#include<conio.h>
#include<string>
#include<map>
using namespace std;
int main(){
map<string, int> student_marks;
student_marks["Farhan Haider"] = 50;
student_marks["Umer Akhlaq"] = 55;
student_marks["Anas Khan"] = 60;
student_marks["Atayyab Owais"] = 65;
student_marks["Farhan Haider"] = 100;
map<string, int>::iterator it = student_marks.begin();
map<string, int>::iterator end = student_marks.end();
for(it; it!=end; ++it){
cout << it->first << " " << it->second << endl;
}
getch();
return 0;
}
int main(){
map<string, int> student_marks;
map<string, int>::iterator it;
student_marks["Farhan Haider"] = 50;
student_marks["Umer Akhlaq"] = 55;
student_marks["Anas Khan"] = 60;
student_marks["Atayyab Owais"] = 65;
student_marks["Farhan Haider"] = 100;
for(it=student_marks.begin(); it!=student_marks.end(); ++it){
cout << it->first << " " << it->second << endl;
}
getch();
return 0;
}
Output:
Note:
The Key "Farhan Haider" was repeated twice in the code. Note the output, the duplicated key repeated in the end in being displayed.
Additional Info:
In a multi map, keys and values both can be duplicated.
Keys(left) and values(right) can be inserted into a Map. Keys are unique while values can be duplicated. Map sorts keys in ascending order by default. Keys and values can be any type of data type like int, string, set, pair and so on.
Lets have a look at the code snippet below:
Basic Code 1:
#include<iostream>
#include<conio.h>
#include<string>
#include<map>
using namespace std;
int main(){
map<string, int> student_marks;
student_marks["Farhan Haider"] = 50;
student_marks["Umer Akhlaq"] = 55;
student_marks["Anas Khan"] = 60;
student_marks["Atayyab Owais"] = 65;
student_marks["Farhan Haider"] = 100;
map<string, int>::iterator it = student_marks.begin();
map<string, int>::iterator end = student_marks.end();
for(it; it!=end; ++it){
cout << it->first << " " << it->second << endl;
}
getch();
return 0;
}
------------------------------ OR ------------------------------
Basic Code 2:int main(){
map<string, int> student_marks;
map<string, int>::iterator it;
student_marks["Farhan Haider"] = 50;
student_marks["Umer Akhlaq"] = 55;
student_marks["Anas Khan"] = 60;
student_marks["Atayyab Owais"] = 65;
student_marks["Farhan Haider"] = 100;
for(it=student_marks.begin(); it!=student_marks.end(); ++it){
cout << it->first << " " << it->second << endl;
}
getch();
return 0;
}
Output:
Note:
The Key "Farhan Haider" was repeated twice in the code. Note the output, the duplicated key repeated in the end in being displayed.
Additional Info:
In a multi map, keys and values both can be duplicated.