C++ Map : Operator [] – Usage Details

In this article we will discuss how to use operator [] with map in C++.

std::map has Operator[] i.e.

mapped_type& operator[] (const key_type& k);

operator [] works in Find or Create Mode i.e. when called with a key K, it will try to look for element with given key K and can go in below 2 directions i.e.

  • If any element is found with key K, then it will return the reference of its value.
  • But if there is no element in map with K, then it will create a new element in map with key K and assign default value of value_type in its value field. Then it will return the value of newly created element as reference.

Let’s discuss it in detail,

Element lookup with Operator[]

Suppose we have a map of String and int i.e.

// Map of string & int i.e. words as key & there
// occurrence count as values
std::map<std::string, int> wordMap = {
					{ "is", 6 },
					{ "the", 5 }
				};

Now suppose, we call the operator [] on above map with key value ‘Hello’.

// As there is no element with key 'Hello'
// So, operator [] will create a new element in map
// with key as 'Hello' and default value, which in this case
// will be 0.
int & value1 = wordMap["Hello"];

As this key ‘Hello’ is not present in map. So operator [] will create a new entry for it with Key ‘Hello’ & Value as default value of int i.e. 0.

Also, will return its value by reference.

Overriding values with operator []

operator [] returns value by reference, so assigning value by calling operator[] can change the value i.e.

// As [] returns the value by reference, therefore
// it will override the new value.
wordMap["is"] = 4;

// Override the value of element with key 'is'
wordMap["is"] = 4;

Checkout the complete example as follows,

#include <iostream>
#include <map>
#include <string>

int main() {

	// Map of string & int i.e. words as key & there
	// occurrence count as values
	std::map<std::string, int> wordMap = {
								{ "is", 6 },
								{ "the", 5 }
							};
	// As there is no element with key 'Hello'
	// So, operator [] will create a new element in map
	// with key as 'Hello' and default value, which in this case
	// will be 0.
	int & value1 = wordMap["Hello"];

	// Display the value
	std::cout<<"value of 'Hello' = "<<value1<<std::endl;

	// Fetch the value for key 'is'
	// As key already exist therefore will not create new entry
	// Will just return the reference of value
	int & value2 = wordMap["is"];

	// Display the value
	std::cout<<"value of 'is' = "<<value2<<std::endl;


	// As [] returns the value by reference, therefore
	// it will override the new value.
	wordMap["is"] = 4;

	int & value3 = wordMap["is"];

	// Display the value
	std::cout<<"value of 'is' = "<<value3<<std::endl;


	// Override the value of element with key 'is'
	wordMap["is"] = 4;

	// Will create a new wntry with Key 'Thanks' and override its
	// default value 0 with 10.
	wordMap["Thanks"] = 10;


	std::cout<< "***********Map Entries***********" <<std::endl;
	// Print the map elements
	for (auto elem : wordMap)
		std::cout << elem.first << " :: " << elem.second << std::endl;

	return 0;
}

Output

value of 'Hello' = 0
value of 'is' = 6
value of 'is' = 4
***********Map Entries***********
Hello :: 0
Thanks :: 10
is :: 4
the :: 5

Using operator[] with User Defined objects as Value

As operator[] can create new entry with default value. So, if we are using a User defined class or struct as value in a map, then its must to have default constructor in it.

Let’s see an example,

#include <iostream>
#include <map>
#include <string>

struct Occurance
{
	int count;

	// Default Constructor
	// Un Comment it to compile the code
	/*
	Occurance()
	{
		this->count = 0;
	}
	*/

	// Parametrized constructor
	Occurance(int count)
	{
		this->count = count;
	}
};
int main() {

	// Map of string & int i.e. words as key & there
	// occurrence count as values
	std::map<std::string, Occurance> wordMap = {
					{ "is", Occurance(6) },
					{ "the", Occurance(5) }
				};


	// As key is not in map, so operator[] will create new entry
	// With default value of value field. Therefore, Will compile
	// only if Occurance sruct has default constructor.
	Occurance occur = wordMap["Hello"];

	return 0;
}

As key is not in map, so operator[] will create new entry with default value of value field. Therefore, above example will compile only if Occurance struct has default constructor. Un-comment it to compile succussfuly.

1 thought on “C++ Map : Operator [] – Usage Details”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top