返回的迭代器map::end
意味着map::find()
在容器中找不到指定的键。您不能取消引用它来访问它的元素。它会使您的应用程序崩溃。
编辑:
让我们清楚一点。问题是你在颠倒逻辑,好吗?您只能使用有效的迭代器,因此iter
必须不同于map::end
. 这意味着map::find()
成功并找到了您正在寻找的元素:
if (iter != imageMap->end())
{
// element FOUND! Use it!
cout << iter->first << endl;
}
else
{
// Not found! Can't use it.
}
您的错误是您当前正在进行的ifif (iter == imageMap->end())
比较:这意味着如果我搜索的元素不在 map 中,则执行以下代码块。这就是为什么在iter->first
执行时应用程序会中断。
#include <iostream>
#include <map>
#include <string>
typedef int ImageData;
typedef std::map<std::string,ImageData*> ImageDataMap;
typedef std::map<std::string,ImageData*>::iterator ImageDataIterator;
using namespace std;
int main()
{
ImageDataMap mymap;
int value_1 = 10;
int value_2 = 20;
int value_3 = 30;
mymap["a"] = &value_1;
mymap["b"] = &value_2;
mymap["c"] = &value_3;
// Search/print valid element
ImageDataIterator it = mymap.find("a");
if (it != mymap.end()) // will execute the block if it finds "a"
{
cout << it->first << " ==> " << *(it->second) << endl;
}
// Searching for invalid element
it = mymap.find("d"); // // will only execute the block if it doesn't find "d"
if (it == mymap.end())
{
cout << "!!! Not found !!!" << endl;
cout << "This statement will crash the app" << it->first << endl;;
}
cout << "Bye bye" << endl;
return 0;
}