开发者

std:map iterator returns badptr on find

I have my std::map defined as

typedef std::map<string,ImageData*> ImageDataMap;
typedef std::pai开发者_开发技巧r<string,ImageData*> ImageDataPair;
typedef std::map<string,ImageData*>::iterator ImageDataIterator;

The above map stores string which is an image file name and ImageData which is the the image metadata. When i use the find as shown below

ImageDataIterator iter =  imageMap->find("Fader.tga");
if(iter == imageMap->end()){...}

The iter->first is a badptr and so it fails the if condition below is. What's wrong here? Running on vc9 express edition on xp64 (the program is 32bit)


An iterator returned as map::end by map::find() means that the specified key was not found in the container. You cannot dereference it to access its elements. It will crash your application.

EDIT:

Let's be clear. The problem is that you are inverting the logic, ok? You can only use an iterator if it's valid, therefore iter must be different from map::end. This means that map::find() was successful and found the element you were looking for:

if (iter != imageMap->end())
{
  // element FOUND! Use it!
  cout << iter->first << endl;
}
else
{
  // Not found! Can't use it.
}

Your mistake is the if comparison you're currently doing: if (iter == imageMap->end()) which means execute the following block of code if the element I searched for is not in the map. That's why when iter->first is executed the application breaks.

#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 you should change if(iter == imageMap->end()){...} to if(iter != imageMap->end()){...}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜