Javatpoint Logo
Javatpoint Logo

C++ map operator[] Function

C++ map operator[] function is used to access the elements in the map with the given key value.

It is similar to the at() function. Only difference between them is that at throws an exception if the accessed key is not present in the map, on the other hand operator [ ] inserts the key in the map if the key is not present already in the map.

Syntax

Consider the key value k, syntax would be:

Parameter

k: Key value of the element whose mapped value is accessed.

Return value

It returns a reference to the mapped value of the element with a key value.

Example 1

Let's see a simple example for accessing the elements.

Output:

Map contains following elements
m['a'] = 1
m['b'] = 2
m['c'] = 3
m['d'] = 4
m['e'] = 5

In the above, operator[] function is used for accessing the elements of map.

Example 2

Let's see a simple example to add the elements using their key values.

Output:

JavaTPoint 

In the above example, operator[] is used to add the elements after initialization using the associated key values.

Example 3

Let's see a simple example to change the value associated with the key value.

Output:

Elements are:
100: Nikita
200: Deep
300: Priya
400: Suman
500: Aman

Elements after make changes are:
100: Nidhi
200: Deep
300: Pinku
400: Suman
500: Arohi

In the above example, operator[] function is used to change the values associated with their key values.

Example 4

Let's see a simple example to differentiate between operator[] and at().

Output:

Java
C++
Python
SQL

Out of Range Exception at map::at

In the above example, when we are using at() function it throws an out_of_range Exception since there is no key with value z in the map and when we use operator[] and add an element in key value d since, there is no key with value 'd' in the map, it insert a key-value pair in map with key 'd' and value = "SQL".

Next TopicC++ Map



Please Share

facebook twitter google plus pinterest