Map is found at STL (standard template library). In C++, STL is a collection of generic classes and functions. Because of STL, reusability of developed code increased. No rewriting of code.
Knowing the definitions of **container ** and **set ** are very important before defining map.
Container: is an object. It is used to store multiple elements. Those elements can be same type or different.
Set: is a special container or data structure that store unique elements of the same type in order. It is a collection of elements with no duplicates. Operations like add, contains, and remove are fast.
The code shown below is used for creating new empty set.
#include
#include // std::set
using namespace std;
int main ()
{
// new set created by the name of set_a
}
Maps: are part of the C++ STL (Standard Template Library) which are associative containers, contains stored key-value pairs with unique keys. In simple words; Map is a collection of pairs (k, v), sometimes called key/value pairs, where v can be found quickly if you know k. Comparison function compare used to store keys. Each key may occur only and only once, thus duplicate keys are not allowed. Operations which have logarithmic complexity are Search, removal, and insertion.
map example_one;
simple example to create map shown on below:
#include
#include
#include
using namespace std;
int main()
{
map example_one;
example_one.insert(pair(1, "wonderful"));
example_one.insert(pair(2, "day"));
cout << example_one[1] << " " << example_one[2] << endl;</code>
return 0;
}
Output for the above code is:
wonderful day
##Use of std::map
The main two uses of std::map is Faster access of data & No duplication of data. Through keys there is a fast access of elements. And every key is unique in the maps so duplication is not an issue.
There are three types of Maps. Let us see them one by one.