map find() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of map::find() function in C++ STL.

What is Map in C++ STL?

Maps are the associative container, which facilitates to store the elements formed by a combination on key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in map container is accessed by its unique keys.

What is map::find()?

The map::find( ) is a function which comes under <map> header file. This function returns an iterator which points to an element of a given key which we want to search.

Syntax

map_name.find(key_value k);

Parameters

This function accepts the following

Parameters

k: This is the key value which we want to search from the map container

Return value

It returns an iterator pointing to the element associated with key k.

Example

Input

map<char, int> newmap;
newmap[‘a’]
= 1;
newmap[‘b’] = 2;
newmap.find(b);

Output

2

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.insert({3, 50});
   TP_Map.insert({2, 30});
   TP_Map.insert({1, 10});
   TP_Map.insert({4, 70});
   cout<<"TP Map is : \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   //to find the map values at position
   auto var = TP_Map.find(1);
   cout<<"Found element at position "<<var->first<<" is : "<<var->second;
   auto var_1 = TP_Map.find(2);
   cout<<"\nFound element at position "<<var_1->first<<" is : "<<var_1->second;
   return 0;
}

Output

TP Map is:
MAP_KEY    MAP_ELEMENT
1             10
2             30
3             50
4             70
Found element at position 1 is : 10
Found element at position 2 is : 30

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.insert({3, 50});
   TP_Map.insert({2, 30});
   TP_Map.insert({1, 10});
   TP_Map.insert({4, 70});
   cout<<"TP Map is : \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.find(2); i!= TP_Map.end(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

Output

TP Map is:
MAP_KEY    MAP_ELEMENT
2             30
3             50
4             70
raja
Published on 15-Apr-2020 12:03:25
Advertisements