std:map iterator在find上返回badptr

我把我的
std::map
定义为
typedef std::map<string,ImageData*> ImageDataMap;
typedef std::pair<string,ImageData*> ImageDataPair;
typedef std::map<string,ImageData*>::iterator ImageDataIterator;
上述地图存储作为图像文件名的字符串和作为图像元数据的
ImageData
。当我使用find如下所示
ImageDataIterator iter =  imageMap->find("Fader.tga");
if(iter == imageMap->end()){...}
iter->first
是一个badptr,因此它失败了下面的if条件。这有什么不对?在xp64上运行vc9 express版(程序是32位)     
已邀请:
迭代器以
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.
}
你的错误是你正在做的比较:
if (iter == imageMap->end())
这意味着如果我搜索的元素不在地图中,则执行以下代码块。这就是为什么当执行
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;
}
    
Perhapes你应该改变
if(iter == imageMap->end()){...}
if(iter != imageMap->end()){...}
    

要回复问题请先登录注册