Map in C++ : Standard Template Library (STL)

What are maps in C++ in STL

1. Maps are used to replicate associative arrays.
2. Maps contain sorted key-value pair in which each key is unique and cannot be changed.
3. Maps can be inserted or deleted but it cannot be altered but the value associated with keys can be altered.
4. No two map values can have the same key values.

Useful Functions of Map class

1. at() : it shows the value present at the iterator. 
2. size() : it shows the size.
3. empty() : it deletes all the elements of the map.
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 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.

How to Create a Map?

map <int, string> customer;
customer [100] = "Nitish";
customer [102] = "Nilima";
customer [109] = "Nishant";


Example:
#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"));
}
 

<< Previous                                                                                      Next >>
Previous
Next Post »