c++ map code example
Example 1: map vs unordered_map in C++
| map | unordered_map
---------------------------------------------------------
Ordering | increasing order | no ordering
| (by default) |
Implementation | Self balancing BST | Hash Table
| like Red-Black Tree |
search time | log(n) | O(1) -> Average
| | O(n) -> Worst Case
Insertion time | log(n) + Rebalance | Same as search
Deletion time | log(n) + Rebalance | Same as search
::-> Use std::map when
1. You need ordered data.
2. You would have to print/access the data (in sorted order).
3. You need predecessor/successor of elements.
::-> Use std::unordered_map when
1. You need to keep count of some data (Example – strings) and no ordering is required.
2. You need single element access i.e. no traversal.
Example 2: map in c
#include <map>
std::map<size_t, std::string> map;
map[10] = "Hello";
map[1] = "boys";
map[901] = "girls"
Example 3: map declaration c++
#include <map>
#include <string>
std::map<int, std::string> map_;
map_[1] = "mercury";
map_[2] = "mars";
map_.insert(std::make_pair(3, "earth"));
return map_[2];
Example 4: map c++
#include <iostream>
#include <string>
#include <map>
using std::string;
using std::map;
int main() {
map<string, int> myMap = {
{"one", 1},
{"two", 2},
{"three", 3}
};
for (auto& iter: myMap) {
std::cout << iter.first << ": " << iter.second << std::endl;
}
}
Example 5: map in c++
#include <bits/stdc++.h>
#include <iostream>
#include <map>
using namespace std;
void mapDemo(){
map<int, int> A;
A[1] = 100;
A[2] = -1;
A[3] = 200;
A[100000232] = 1;
map<char, int> cnt;
string x = "Sumant Tirkey";
for(char c:x){
cnt[c]++;
}
cout<< cnt['a']<<" "<<cnt['z']<<endl;
}
int main() {
mapDemo();
return 0;
}
Example 6: map in cpp
#include <map>
map<int, int> gquiz1;
gquiz1.insert(pair<int, int>(1, 40));