Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 the end is undefined behavior, best case is that the app crashes, worst case 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading