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:



Table Of Contents