我正在尝试使用 std::map::find 方法通过某个键获取迭代器。但是,我得到了一些有效的迭代器,但与映射的键对应的对的第一个值在映射中不存在。这是代码:
#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 ;
}
我输入2个整数
4 5
,输出是1 , 0
,但是点中不存在键(1,0)。这种行为的原因是什么?
我期望得到
points.end()
,因为这个键在点中不存在。
当 map.find() 在地图中找不到值时,它返回
map.end()
指向“无处”,当它指向末尾时使用此迭代器是未定义的行为,最好的情况是应用程序崩溃,最坏的情况是应用程序继续在错误的状态下工作并产生垃圾,请始终检查.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