What is a Map in C++ with Example?
Map in C++ is used to replicate associative arrays. It contains a sorted key-value pair in which each key is unique and cannot be changed. It can be inserted or deleted but it cannot be altered but the value associated with keys can be altered. No two map values in C++ can have the same key values.
Useful Functions of Map class in C++
1. at() : it shows the value present at the iterator.Â
2. size() : it shows the size.
3. empty() : it deletes all the map elements.
4. clear() : removes all the elements from the map.
5. begin() : return the iterator to the first element in the map.
6. end() : return the iterator to the last element in the map.
7. max_size() : returns the maximum number of elements that the map can hold.
8. pair_insert(keyvalue, mapvalue) : it adds a new element to the map.
9. erase(iterator_position) : removes the elements at the position pointed by the iterator.
10. erase(const_n) : removes the key value 'n' from the map.
begin() and end() Functions:
begin(): Returns an iterator to the first element in the map.
end(): Returns an iterator to the theoretical element that follows the last element in the map.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> mp;
mp["one"] = 1;
mp["two"] = 2;
mp["three"] = 3;
for (auto it = mp.begin(); it != mp.end(); ++it) {
cout <lt; "Key: " <lt; it->first <lt; ", Value: " <lt; it->second <lt; endl;
}
return 0;
}
How to Create a Map in C++
map <int, string> customer; customer [100] = "Nitish"; customer [102] = "Nilima"; customer [109] = "Nishant";
#include<iostream>
#include<map>
using namespace std;
int main(){
map <int, string> customer;
customer[100] = "Gajendra";
customer[123] = "Dilip";
customer[145] = "Aditya";
customer[171] = "Shahid";
customer[200] = "Rajesh";
map <int, string> customer2 {
{100, "Gajendra"}, {123, "Dileep"},
{145, "Aditya"}, {171, "Shahid"},
{200, "Rajesh"} };
map <int, string> :: iterator P = customer.begin();
while(P!=customer.end()) {
cout << P->second << endl;
P++;
}
cout << customer.at(145); //Aditya
cout << customer.size(); //5
cout << customer.empty(); //0
customer.insert(pair<int, string> (205, "NKS"));
}