1#include <iostream>
2#include <string>
3#include <map>
4
5using std::string;
6using std::map;
7
8int main() {
9 // A new map
10 map<string, int> myMap = { // This equals sign is optional
11 {"one", 1},
12 {"two", 2},
13 {"three", 3}
14 };
15
16 // Print map contents with a range-based for loop
17 // (works in C++11 or higher)
18 for (auto& iter: myMap) {
19 std::cout << iter.first << ": " << iter.second << std::endl;
20 }
21}
1//Since c++17
2for (auto& [key, value]: myMap) {
3 cout << key << " has value " << value << endl;
4}
5//Since c++11
6for (auto& kv : myMap) {
7 cout << kv.first << " has value " << kv.second << endl;
8}
1#include<bits/stdc++.h>
2using namespace std;
3
4int main()
5{
6 map<string,int>mapa;
7 for(int i=0;i<10;i++){
8 int x;
9 string s;
10 cin>>x>>s;
11 mapa.insert({s,x});
12 }
13 for(auto [x,y]:mapa){
14 cout<<x<<" "<<y<<'\n';
15 }
16}
1//assuming your variables are called : variables_
2#include <map>
3#include <string>
4
5std::map<int, std::string> map_;
6map_[1] = "mercury";
7map_[2] = "mars";
8map_.insert(std::make_pair(3, "earth"));
9//either synthax works to declare a new entry
10
11return map_[2]; //here, map_[2] will return "mars"
1// map::at
2#include <iostream>
3#include <string>
4#include <map>
5
6int main ()
7{
8 std::map<std::string,int> mymap = {
9 { "alpha", 0 },
10 { "beta", 0 },
11 { "gamma", 0 } };
12
13 mymap.at("alpha") = 10;
14 mymap.at("beta") = 20;
15 mymap.at("gamma") = 30;
16
17 for (auto& x: mymap) {
18 std::cout << x.first << ": " << x.second << '\n';
19 }
20
21 return 0;
22}
1#include <bits/stdc++.h>
2#include <iostream>
3#include <map>
4using namespace std;
5void mapDemo(){
6 map<int, int> A;
7 A[1] = 100;
8 A[2] = -1;
9 A[3] = 200;
10 A[100000232] = 1;
11 //to find the value of a key
12 //A.find(key)
13
14 //to delete the key
15 //A.erase(key)
16
17 map<char, int> cnt;
18 string x = "Sumant Tirkey";
19
20 for(char c:x){
21 cnt[c]++;//map the individual character with it's occurance_Xtimes
22 }
23
24 //see how many times a and z occures in my name
25 cout<< cnt['a']<<" "<<cnt['z']<<endl;
26
27}
28
29int main() {
30 mapDemo();
31 return 0;
32}