| by Arround The Web | No comments

C++ Unordered_Map::Find() Function

C++ is renowned for its powerful and versatile standard template library (STL), providing the developers with an extensive suite of ready-to-use, highly efficient containers, iterators, algorithms, and functions. Among these, the “unordered_map” stands out as a key player in efficient key-value storage and high-speed access, making it an excellent choice for applications where fast retrieval is paramount. In the heart of this “unordered_map”, the unordered_map::find() function is a vital instrument. This data structure is optimized for high-speed access and key-value storage. This article offers a comprehensive examination of the unordered_map::find() function by unveiling its syntax and parameters with the help of illustrative examples.

Understanding the Unordered_Map::Find()

The unordered_map::find() function is designed to locate an element that is associated with a specified key within an “unordered_map”. Its declaration varies based on whether the object is constant-qualified or not, providing flexibility in its usage.

iterator find (const key_type& k);

This is used when the “unordered_map” is not constant-qualified. This code returns an iterator that points to the found element.

const_iterator find (const key_type& k) const;

This version is applicable when the “unordered_map” is constant-qualified. It returns a constant iterator with a similar behavior to the non-constant version.

Parameters:

It takes a single parameter, “k”, which is the key to be searched within the “unordered_map”.

Return Value:

The return value depends on the qualification of the “unordered_map” object.

The method returns a non-constant iterator if the object is not constantly qualified.

If the object is constant-qualified, the method returns a constant iterator.

Time Complexity:

The time complexity of std::unordered_map::find() is crucial for understanding its efficiency:

In the average case, the time complexity is constant (O(1)), making it highly efficient for typical use cases.

In the worst-case scenario, the time complexity becomes linear (O(n)). However, this scenario is rare in practice.

Example 1:

Let’s explore a practical example to illustrate the usage and benefits of unordered_map::find(). In this example, an “unordered_map” is created with the characters as keys and the corresponding integers as values. The find() function locates the element that is linked with the key of “p”. The “ittr” iterator is linked to the found element and its data are printed to the console. See the following code:

#include <iostream>

#include <unordered_map>

using namespace std;

int main(void) {

  unordered_map<char, int> unomp = {

  {'w', 9},

  {'a', 6},

  {'p', 8},

  {'m', 3},

  {'s', 4} };

  auto ittr = unomp.find('p');

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

  return 0;}

Let’s breakdown the code to have a clear and better understanding of it:

#include <iostream>

#include <unordered_map>

The necessary header files are included: <iostream> for input/output operations and <unordered_map> for using the “unordered_map” container.

using namespace std;

The “std” namespace simplifies the code. It lets you use the elements from the standard C++ library without prefixing them with “std::”.

unordered_map<char, int> unomp = { {'w', 9}, {'a', 6}, {'p', 8}, {'m', 3}, {'s', 4} };

An “unordered_map” named “um” is created with the characters (‘w’, ‘a’, ‘p’, ‘m’, ‘s’) as keys and the corresponding integers (9, 6, 8, 3, 4) as values.

auto ittr = unomp.find('p');

The find() function is used to search for the element with the key of “p” in the “unordered_map” which is “unomp”. The “ittr” iterator points to the identified element.

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

The content that is pointed to by the iterator is printed to the console. It prints the key (“p”) and the associated value (8) in this case.

return 0;

The program terminates, returning 0 to indicate a successful execution.

The output of the code is given in the following for your reference:

This code is a simple example of utilizing the unordered_map::find() to efficiently search for and access the elements within an “unordered_map”. The iterator provides a convenient way to access both the key and the associated value of the found element.

Example 2:

Here is another simple example of the unordered_map::find() function. This code demonstrates the usage of “unordered_map” to store the Boolean values associated with integer keys and then utilizes the find() function to check for the existence of specific keys. Let us see the following code and then understand how it works:

#include <bits/stdc++.h>

using namespace std;

int main() {

  unordered_map<int, bool> unomp;

  unomp[2] = true;

  unomp[67] = false;

  unomp[45] = true;

  unomp[98] = false;

  if (unomp.find(67) == unomp.end())

  cout << "Element not found"<<endl;

  else

  cout << "Element found"<<endl;

  if (unomp.find(42) == unomp.end())

  cout << "Element not found"<<endl;

  else

  cout << "Element found"<<endl;

  return 0;

}

Here is a detailed description of the code:

#include <bits/stdc++.h>

This line includes a header file that covers the most standard C++ libraries that are often used in competitive programming. However, in a regular C++ development, it’s recommended to include the specific headers.

unordered_map<int, bool> unomp;

An “unordered_map” named “unomp” is created with integer keys and Boolean values.

unomp[2] = true;

unomp[67] = false;

unomp[45] = true;

unomp[98] = false;

The key-value pairs are inserted into the “unordered_map”. Each key (integer) is associated with a Boolean value.

if (unomp.find(67) == unomp.end())

  cout << "Element not found" << endl;

else

  cout << "Element found" << endl;

The find() function is employed within the if-else condition to search for specific keys (67 and 42) within the “unordered_map”. If the key is found, “Element found” is printed. Otherwise, “Element not found” is printed. See the following output:

This code showcases the basic usage of “unordered_map” and the find() function to determine the presence or absence of specific keys in the map.

Example 3:

Let us explore another example that demonstrates the finding of a value by providing an input at run time. This simple program uses an “unordered_map” to store the names (as keys) and associated numerical values (in this case, representing some attributes). It then prompts the user to enter a name, search for that name in the map using the find() function, and print the associated value if the name is found. The code is given in the following for your reference:

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main (){

  std::unordered_map<std::string,double> unomp = {

  {"Herry",2.3},

  {"Andre",7.4},
 
  {"Kalsoom",1.2} };

  string who;

  cout << "Who are you looking for? ";

  getline (cin,who);

  unordered_map<string,double>::const_iterator fnd = unomp.find (who);
 
  if ( fnd == unomp.end() )

    cout << "not found";

  else

    cout <<endl<< fnd->first << " is " << fnd->second<<endl;

  return 0;

}

The following is the breakdown of the code for your understanding:

unordered_map<string, double> unomp = {};

An “unordered_map” named “unomp” is created with string keys (names) and double values.

string who;

The user is prompted to enter a name on the screen and the input is stored in the “who” string variable.

unordered_map<string, double>::const_iterator fnd = unomp.find(who);

The find() function is used to search for the entered name in the “unordered_map”. The result is stored in the “fnd” iterator.

if (fnd == unomp.end())

cout << "not found";

else

cout << endl << fnd->first << " is " << fnd->second << endl;

If the “fnd” iterator reaches the end of the “unordered_map” (end()), it means that the name was not found and “not found” is printed. Otherwise, the name and its associated value are printed. Here is the output of the code:

This code essentially acts as a simple name lookup tool using an “unordered_map”. It takes the user input, searches for the name in the map, and provides the associated value if the name is found.

Conclusion

The unordered_map::find() function in C++ provides a powerful mechanism to efficiently locate the elements within “unordered_map” containers. Its constant average time complexity makes it a preferred choice for search operations in scenarios where the key-value pairs must be accessed swiftly. The provided examples showcase its practical usage, emphasizing its simplicity and effectiveness. In conclusion, mastering the unordered_map::find() function enhances a C++ programmer’s ability to harness the full potential of “unordered_map” containers, contributing to the creation of optimized and high-performance applications.

Share Button

Source: linuxhint.com

Leave a Reply