C++

C++ Map Search

“The associating container known as a map allows for the storage of elements in C++ that result from the interaction of a key-value pair and mapped data in a particular sequence. The relevant keys in a map container are always used to properly organize the information. By using its specific keys, a map container’s values can be retrieved. To retrieve the data from the container, we used the map::search() function, which appears in the header file <map>.

Map::search() is a built-in function in C++ STL ( Standard Template Library) that provides an iterator or a static iterator that points to the location in the map in which the key is located. It produces an iterator or a static iterator that references the map; if the key isn’t available in the container, then map.end() function is called.”

Advantages of map::search() Function in C++

The std::map object’s benefits include quick search, inclusion, and removing actions that can be completed in logarithmic time. The find component, which receives a reference to a key, offers the search function. The iterator to the relevant component is produced if the specified key can be located in the std::map object. The previous iterator (map::end()) is given if, on the contrary hand, the provided key is not located in the container.

Syntax of map::search() Function in C++

Here is the syntax of map::search() function in C++.

“OR”

Parameters in map::search() Function in C++

Specifying the key to find in the map containers is the only required parameter that the map::search() function allows.

Returned Value in map::search() Function in C++

The function’s calculated value is either an iterator or a constant iterator that points to the location of the key in the map. If somehow the key is absent from the map containers, the function will return an iteration or a static iteration that points to the map.end () function.

Runtime Completion for Search Component

Finding components in a std::map search() function takes O(log n) time to complete. Because there is internal storage of items as a Balancing Binary Search Tree (BST), even in the worst scenario, it should be O(log n) compared to std::string. In contrast, the ideal case time complexity for finding is O(1) because components are kept in a Relational table, and the key serves as an indicator when trying to search in unsorted maps.

Example 01: Use the map::search() Function to Search the Component With a Provided Key Value in C++

Here is the following code snippet; we have used the map::search() function in C++ to find the key where it is located. In our code, firstly, we have added the header file “iostream,” which is a standard input-output stream for objects like cin, cout, etc. Then add the “map” header file that holds organized key-value pairs, where each key is distinct and may only be added or removed. Then, we used standard “namespace std” in our code because more than one variable, function, class, etc., cannot share the same identity within the exact context in C++.

#include <iostream>
#include <map>
using namespace std;

The main() method, which has been created to begin the execution of code, was then provided. In the main() function, firstly, we have declared a variable “n” of data type “integer”. The “map<int, string> m1” container contains an arranged dataset containing key values, and “m1” is a member of the associated containers in the C++ standard template library. Keep in mind that keys in the “map<int, string>” container are exclusive. As a result, if new items are added while using the current keys, nothing happens. However, if the keys coincide, some unique member functions in the “map<int, string>” container can add new data to the preexisting pairs.

After that, “cout” is used to print the exact line of information written in quotation marks. Then “cin” is used to take the input from the user. Then the “auto” keyword is used to find the item in the “m1” container.

int main()
{
    int n;  
    map m1 = {{1 , "Hello"},
                           {2 , "Java"},
                           {3 , "Python"},
                           {4 , "Ruby"},
                           {5 , "React"},
                           {6 , "Angular"},};
                           
    cout<>n;  
    auto item = m1.find(n);

After the declaration, the if-else condition is used. In the if statement, we check the item if it is available in container m1, then print the item. If it is not in the “m1” container, it shows the error message which was written in the “cout”.

    if (item != m1.end())
    {
        cout << "Key exists!" << endl << "The Key at index "
             <first << " is " <second << endl;
    }
    else
    {
        cout <<"Key does not exist!" << endl << "Sorry for inconvenience."
             << endl <<"Please try again with correct key index from 1 to 6";
    }

 

At the end of the main() function, we will return the “EXIT_SUCCESS” that indicates that the program is successfully executed.

return EXIT_SUCCESS;
}

Here is the full illustration of the map::search() function, which is employed to locate the component using the user-provided key value.

After compiling the above program, it will show the following message that the user has to enter the key index which she/he wants to find. Users have to enter the key index from the 1 to 6 range.

As you can see below, when the user enters the 1 key index, it shows the message that the “Key Exists!” and the key at index 1 is “Hello”.

If the user enters the index key above the range of 1 to 6, then the compiler generates the error message that “please, try again with the correct index key from 1 to 6”.

Example 02: Use the map::search() Function to Display All of the Components After Discovering a Component

Let us take another example to print all the random order components after discovering a component. To prevent any problems during compiling and code execution, we have included the “bits/stdc++.h” header file in the code. The main() function has been initialized after the header library and “namespace std” have been added. In the main() function, we initialized the m1 container. Then values are inserted in random order. After that “cout” statement is used to print the output, the same written in quotation marks. Then “for” condition is applied to find the position at which “2” is present by using the find() function. Then return 0, which implies that the program is successfully executed.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    map m1;
   
    m1.insert({ 2, 101 });
    m1.insert({ 1, 689 });
    m1.insert({ 3, 350 });
    m1.insert({ 6, 991 });
    m1.insert({ 4, 541 });
    m1.insert({ 5, 542 });

    cout << "Elements from position 2 onward are: "<<endl;
    cout << "KEY\tELEMENT"<<endl;

    for (auto iterator = m1.find(2); iterator != m1.end(); iterator++)
    {
        cout <first << '\t' <second <<endl;
    }

    return 0;
}

Here is the output of the compiled program:

Conclusion

This article has come up with enough examples to illustrate the functioning of the map::search() method of C++ language. We have discussed the map::search() working in C++. We have also discussed the advantages, parameters, and returned value of the map::search() function. In the end, we have compiled some examples to help the user search for the component with a key value in C++.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.