|
| 1 | +#include <iostream> |
| 2 | +#include <map> |
| 3 | +#include <unordered_map> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +int main() { |
| 7 | + |
| 8 | + // creation of Unordered Map |
| 9 | + unordered_map<string, int> um; |
| 10 | + |
| 11 | + // insertion |
| 12 | + // Approach 1 |
| 13 | + pair<string, int> p = make_pair("Hello", 1); |
| 14 | + um.insert(p); |
| 15 | + |
| 16 | + // Approach 2 |
| 17 | + pair<string, int> p2("World", 2); |
| 18 | + um.insert(p2); |
| 19 | + |
| 20 | + // Approach 3 |
| 21 | + pair<string, int> p3{"NewWorld", 3}; |
| 22 | + um.insert(p3); |
| 23 | + |
| 24 | + // Approach 4 |
| 25 | + um["World"] = 4; |
| 26 | + |
| 27 | + |
| 28 | + cout << "-------- Searching --------" << endl; |
| 29 | + // Searching |
| 30 | + // Approach 1 |
| 31 | + cout << "Value of 'World' Key : "<< um["World"] << endl; |
| 32 | + |
| 33 | + // Approach 2 |
| 34 | + cout << "Value of 'World' Key : " <<um.at("NewWorld") << endl; |
| 35 | + |
| 36 | + // Search for Un-known key |
| 37 | + // cout << um.at("unknown") << endl; // output : error |
| 38 | + // cout << um["unknown"] << endl; // output : 0 |
| 39 | + |
| 40 | + // But now change the order at see what it returns. |
| 41 | + cout << "Value of 'unknown' Key : " << um["unknown"] << endl; // output : 0 |
| 42 | + cout << "Value of 'unknown' Key : " << um.at("unknown") << endl; // output : 0 |
| 43 | + |
| 44 | + // Updation |
| 45 | + um["World"] = 5; |
| 46 | + |
| 47 | + cout << "-------- Checking Size --------" << endl; |
| 48 | + // Size |
| 49 | + cout << "Size of unordered_map : " << um.size() << endl; |
| 50 | + |
| 51 | + cout << "-------- Check Presence --------" << endl; |
| 52 | + // Check Presence |
| 53 | + cout << "Is 'World' Key Value Present or Not : "<< um.count("World") << endl; // true |
| 54 | + cout << "Is 'Unknown' Key Value Present or Not : "<< um.count("Unknown") << endl; // false |
| 55 | + |
| 56 | + // Erase |
| 57 | + um.erase("World"); |
| 58 | + cout << "Size of unordered_map : " << um.size() << endl; |
| 59 | + |
| 60 | + cout << "-------- For Loop Iteration --------" << endl; |
| 61 | + // Iteration |
| 62 | + for(auto i : um) cout << "Iterting Key Value Pair : " << i.first << " " << i.second << endl; |
| 63 | + |
| 64 | + cout << "-------- Iterators --------" << endl; |
| 65 | + // Iterators |
| 66 | + unordered_map<string, int> :: iterator it = um.begin(); |
| 67 | + |
| 68 | + while(it != um.end()){ |
| 69 | + cout << "Iterting Key Value Pair : " << it->first << " " << it->second << endl; |
| 70 | + it++; |
| 71 | + } |
| 72 | + return 0; |
| 73 | +} |
0 commit comments