Searching in std::map or in std::multimap

suggest change

There are several ways to search a key in std::map or in std::multimap.

std::multimap< int , int > mmp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} };
auto it = mmp.find(6);
if (it!=mmp.end())
    std::cout << it->first << ", " << it->second << std::endl; //prints: 6, 5
else
    std::cout << "Value does not exist!" << std::endl;

it = mmp.find(66);
if (it!=mmp.end())
    std::cout << it->first << ", " << it->second << std::endl; 
else
    std::cout << "Value does not exist!" << std::endl; // This line would be executed.
std::map< int , int > mp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} };
if (mp.count(3) > 0) // 3 exists as a key in map
    std::cout << "The key exists!" << std::endl; // This line would be executed.
else
    std::cout << "The key does not exist!" << std::endl;

If you only care whether some element exists, find is strictly better: it documents your intent and, for multimaps, it can stop once the first matching element has been found.

auto eqr = mmp.equal_range(6);
auto st = eqr.first, en = eqr.second;
for (auto it = st; it != en; ++it){
    std::cout << it->first << ", " << it->second << std::endl; 
}
    // prints: 6, 5
    //         6, 7

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::map:
* Searching in std::map or in std::multimap

Table Of Contents
8 Arrays
11 Loops
26 std::map
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype