C++ Map Find Function

In C++, the Standard Template Library (STL) provides many containers for storing and managing data efficiently. One of the most used and most powerful associative containers is the std::map. As an associative container, it contains elements that consist of a key and a value in a sorted order. It enables us to perform several operations, such as insertion, deletion, and retrieval operations.

One of the most frequently used member functions of std::map is the std::map::find function. This member function enables a programmer to search for an element by its key quickly and efficiently.

In C++ , the map find function is commonly utilized to find an element with the given key value k. If it finds the element, it returns an iterator thacpp tutorials to the element. Otherwise, it returns an iterator pointing to the end of the map container , i.e., map::end.

Syntax:

It has the following syntax:

Example

iterator find (const key_type& k);      // until C++ 11

const_iterator find (const key_type& k) const;     //since C++ 11

In this syntax,

  • k: It specifies the key to be searched in the map container.
  • Return value

If it finds the element in the map container, it returns an iterator pointing to the element. Otherwise, it returns an iterator pointing to the end of the map, i.e., map::end.

C++ Simple map find Function Example

Let's take a simple example to find the element with the given key value using the map find function in C++.

Example

Example

#include <iostream>  

#include <map>  

using namespace std;     //using standard namespace

int main(void) {    //main function

   map<char, int> m = {  

            {'a', 100},  

            {'b', 200},  

            {'c', 300},  

            {'d', 400},  

            {'e', 500},  

            };  

   auto it = m.find('c');  

   cout << "Iterator points to " << it->first <<   

      " = " << it->second << endl;  

     return 0;  

}

Output:

Output

Iterator points to c = 300

Explanation:

In this example, we have a character map named m that searches for the key 'c' in the map container. If the key is found in the map container, it returns an iterator thacpp tutorials to that key-value pair. After that, the program prints the key and its associated value, which shows how to use the find function efficiently, which searches elements in a map.

C++ map find Function Example with Condition Check

Let's take a simple example to illustrate how to find the element with a condition check using the map find function in C++.

Example

Example

#include <iostream>  

#include <map>  

using namespace std;    //using standard namespace

int main(void) {    //main function

   map<char, int> m = {  

            {'a', 100},  

            {'b', 200},  

            {'c', 300},  

            {'d', 400},  

            {'e', 500},  

            };      

    auto it = m.find('e');  

         if ( it == m.end() ) {  

    // not found  

     cout<<"Element not found";  

    }   

    else {  

        // found  

        cout << "Iterator points to " << it->first << " = " << it->second << endl;  

    }  

         return 0;  

}

Output:

Output

Iterator points to e = 500

Explanation:

In this example, we use the std::map::find function to search for the key 'e' in the map. If the key is not found, the iterator returned by the find function equals m.end, and it prints the message "Element not found". If the key is found in the map container, it prints the key and its corresponding value.

C++ std::map find Function Example with User Input

Let us take an example to illustrate the map find function with user input in C++.

Example

Example

#include <iostream>

#include <map>  

 using namespace std;    //using standard namespace

int main()    //main method

{  

    int n;  

    map<int,char> example = {{1,'a'},{2,'b'},{3,'c'},{4,'d'},{5,'e'} };   

    cout<<"Enter the element which you want to search: ";  

    cin>>n;  

       auto search = example.find(n);  

    if (search != example.end()) {  

        cout << n<<" found and the value is " << search->first << " = " << search->second << '\n';  

    } else {  

        cout << n<<" not found\n";  

    }  

}

Output:

Output

Enter the element which you want to search: 4

4 found and the value is 4 = d

Explanation:

In this example, we use the std::map::find function to search for a user-specified key in a map. After that, it prompts the user to enter a key value, and then it checks whether it exists in the map. If the element is found, it prints the key and its associated value; otherwise, it displays a message indicating that the element was not found.

C++ std::map find Function Example to Erase an Element

Let's take an example to demonstrate the map find function to erase an element in C++.

Example

Example

#include <iostream>  

#include <map>  

  

using namespace std;    //using standard namespace

  int main ()     //main function

{  

  map<char,int> mymap;  

  map<char,int>::iterator it;  

   mymap['a']=50;  

  mymap['b']=100;  

  mymap['c']=150;  

  mymap['d']=200;  

  it = mymap.find('b');  

  if (it != mymap.end())  

    mymap.erase (it);  

  // print content:  

  cout << "Elements in mymap:" << '\n';  

  cout << "a => " << mymap.find('a')->second << '\n';  

  cout << "c => " << mymap.find('c')->second << '\n';  

  cout << "d => " << mymap.find('d')->second << '\n';    

  return 0;  

}

Output:

Output

Elements in mymap:

a => 50

c => 150

d => 200

Explanation:

In this example, we have utilized the std::map::find function to locate the key 'b' in the map container. If the key is found in the map container, it uses the erase function to remove that key-value pair from the map. After deleting the element, it prints the remaining elements.

Features of the map find function in C++

There are several features of the map find function in C++. Some of them are as follows:

  • In C++ programming, each key in the map should be unique, and the values will be sorted (the key-value pairs are sorted on the key).
  • A std::map in C++ is almost always implemented as a balanced binary search tree, usually a Red-Black Tree.
  • The elements are sorted based on the key.
  • The time complexity for a lookup, insertion, or deletion is O(log n).
  • The std::map function allows for iterators, and it is possible to traverse the map in ascending key order.
  • Conclusion

In conclusion, the map::find function in C++ is a simple and effective method for searching for a key in an ordered associative container. It is commonly utilized to check whether a key exists in the map container. If the key is present in the container, we can retrieve the associated value. These operations can be performed with logarithmic time complexity, given the underlying Red-Black Tree structure of the map. Unlike the operator, no new elements will be added, which makes it perfect for safe lookups and validations.

C++ Map find function FAQs

1) What does the map::find function return if the key is not found in C++?

In the C++ programming language, if the key is not found in the map container, the map::find function will return an iterator to map.end, which indicates that the element does not exist in the map.

2) Can the map::find function insert new elements into the map in C++?

No, the map::find function doesn't insert new elements into the map container. The find function has read-only semantics. It only looks for a key and does not apply any updates or insert elements into the container.

3) What is the time complexity of the map::find function in C++?

In C++, the lookup also has a time complexity of O(log n) because the map is implemented as a balanced binary search tree.

4) How is the map::find function different from operator in C++?

In C++, the distinction between the map::find and operator function is that the map::find will simply check and return an iterator if the key exists. In contrast, the operator will instantiate a new element with a default value if the key is missing, which means the map could be changed accidentally.

5) Can we use the map::find function with a constant map in C++?

Yes, we can use the map::find function with the constant map in C++. When we use the find function in conjunction with a const map, the find function will return a const_iterator, which means that it will search and read elements but will not allow us to modify any elements.

Input Required

This code uses input(). Please provide values below: