Search code examples
c++iteratorstdmap

std::map::find finds non-existing key


I'm trying to get iterator by some key using a std::map::find method. However, I get some valid iterator, but it's first value of pair corresponding to map's key does not exist in map. Here is the code:

#include <iostream>
#include <array>
#include <map>
int main()
{
    int x, y;
    std::map<std::pair<int,int>,bool> points;
    std::array<std::map<std::pair<int,int>,bool>::iterator, 4> prev_iter;
    std::cin >> x >> y;
    points[{x,y}] = false;

    prev_iter[0] = points.find({x-4, y});
    std::cout <<  prev_iter[0]->first.first <<" , "
    <<  prev_iter[0]->first.second ;
}

I enter 2 integers 4 5 , and the output is 1 , 0, but key (1,0) does not exist in points. What is the reason for such behaviour?

I expected to get points.end(), because this key does not exist in points.


Solution

  • When map.find() doesn't find the value in the map, it returns map.end(), which points "nowhere". Using this iterator when it points to nowhere is undefined behavior. Best case is the app crashes, worst case is the app keeps working in a wrong state and produce garbage. Always check against .end():

    #include <map>
    #include <iostream>
    
    int main()
    {
        std::map<int,int> map{{4,5}};
        const auto it = map.find(1);
        if (it != map.end())
        {
            std::cout << "value " << it->second <<  " found!" << '\n';
        } 
        else
        {
            std::cout << "value not found!" << '\n';
        }
    }
    

    value not found