Hello everyone, In this article, we will see different ways by which we can check if a particular key exists in a map or not. Let’s first go through what a map is:

C++ map stores information in <key, value> pairs and we can access the value field from the key in O(logn) time. Now the problem is to check if there exists a particular key in the map or not.

Method 1: Using map::find

We can take the help of the standard library function find for map. map::find returns an iterator to the <key, value> pair if the key exists or it points to the standard iterator end in the map. So if for any particular key if find is returning an iterator pointing to the standard operator end then we can say that map doesn’t have that particular key. Here is the code: 

#include <bits/stdc++.h>

using namespace std;

int main() {
	map<int, int> mp = {	
							{1,1},
							{2,4},
							{3,9},
							{4,16},
							{5,25}
						};
	
	if(mp.find(2) != mp.end()) {
		cout<<"Key found. Value is: "<<mp[2]<<endl;
	}
	else {
		cout<<"Key not found.";
	}
	
	if(mp.find(7) != mp.end()) {
		cout<<"Key found. Value is: "<<mp[7]<<endl;
	}
	else {
		cout<<"Key not found.";
	}
	
}

The time complexity to check is the same as map::find function which is O(logn).

Method 2: Using map::count

We can also make use of the c + + count method which returns 1 if the particular key is present otherwise returns 0. Here is the code illustrating the same:

#include <bits/stdc++.h>

using namespace std;

int main() {
	map<int, int> mp = {	
							{1,1},
							{2,4},
							{3,9},
							{4,16},
							{5,25}
						};
	
	if(mp.count(2) > 0) {
		cout<<"Key found. Value is: "<<mp[2]<<endl;
	}
	else {
		cout<<"Key not found.";
	}
	
	if(mp.count(7) > 0) {
		cout<<"Key found. Value is: "<<mp[7]<<endl;
	}
	else {
		cout<<"Key not found.";
	}
	
}

The time complexity for the above code is O(logn) as well. This is widely used to check if a key is present or not.

Note: If the particular key is not present and if somewhere we use it then the key will be created in the map and initiated default value (0 for int. “” for string) will be created. So never check a key exists or not with the below condition:

if(mp[key] == 0) {
	cout<<"Key doesn't exist";
}

Check the below code for better understanding: 

#include <bits/stdc++.h>

using namespace std;

int main() {
	map<int, int> mp;
	cout<<mp[0]<<endl; // Prints 0
	
	map<int, string> mpp;
	cout<<mpp[0]<<endl; // Prints ""
}

The post C++ Map Check if Key Exists – 2 Ways to Check appeared first on The Crazy Programmer.

0 0 vote
Article Rating

This post was originally published on this site