# C++ map having key as a user defined data type

A map is a data structure that stores information in the form of key and value pairs. In C++, map is defined in STL (standard template library) and store keys in an ordered form.

Syntax to define a map

map<key_type , value_type> map_name;

The data type of any of these two data of the map can be any of the data types. We can have any of the primary data types or derived data types as key or value data types in a map.

We can use any of the data types as the data type of the key of the map. Even a user-defined data type can be used as key data type.

Now, we will create a data structure that defines a new data type. And use it as a key for the map.

## Syntax

struct key{
float f;
}

Using this user-defined data type in the map created the programmer can get a more informative data set from the map. A struct can have any number of data’s in it, even arrays and other data structures are valid to be taken under consideration in this case.

## Example

#include <bits/stdc++.h>
using namespace std;
struct kdata {
float id;
};
bool operator<(const kdata& t1, const kdata& t2){
return (t1.id < t2.id);
}
int main(){
kdata t1 = { 4.5 }, t2 = { 12.3 }, t3 = { 67.8 }, t4 = { 65.2 };
map<kdata, char> maps;
maps[t1] = a;
maps[t2] = h;
maps[t3] = m;
maps[t4] = q;
cout<<"The map data is ";
for (auto x : maps)
cout << x.first.id << " > " << x.second << endl;
return 0;
}

## Output

The map data is
4.5 > a
12.3 > h
67.8 > m
65.2 > q

Advertisements