C++ map search key

Introduction

To search for a specific key inside a map, we can use the map's .find(key_value) member function, which returns an iterator.

If the key was not found, this function returns an iterator with the value of .end().

If the key was found, the function returns the iterator pointing at the pair containing the searched-for key:

#include <iostream> 
#include <map> 

int main() // w w w.  j av a 2s. c o  m
{ 
    std::map<int, char> mymap = { {1, 'a'}, {2, 'b'}, {3,'z'} }; 
    auto it = mymap.find(2); 
    if (it != mymap.end()) 
    { 
        std::cout << "Found: " << it->first << " " << it->second << '\n'; 
    } 
    else 
    { 
        std::cout << "Not found."; 
    } 
} 

Iterator now points at a map element.

Map elements are pairs that consist of the first element - the key and the second element - the value.

To access these using an iterator, first we must dereference an iterator using the arrow operator ->.

Then we call the pair's first member variable for a key and second for a value.




PreviousNext

Related