C++ Map Library - find() Function


Advertisements


Description

The C++ function std::map::find() finds an element associated with key k.

If operation succeeds then methods returns iterator pointing to the element otherwise it returns an iterator pointing the map::end().

Declaration

Following is the declaration for std::map::find() function form std::map header.

C++98

iterator find (const key_type& k);
const_iterator find (const key_type& k) const;

Parameters

k − Key to be searched.

Return value

If object is constant qualified then method returns a constant iterator otherwise non-constant iterator.

Exceptions

This member function doesn't throw any exception.

Time complexity

Logarithmic i.e. O(log n)

Example

The following example shows the usage of std::map::find() function.

Live Demo
#include <iostream>
#include <map>

using namespace std;

int main(void) {
   map<char, int> m = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5},
            };

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

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

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Iterator points to c = 3

map.htm

Advertisements