gpt4 book ai didi

c++ - 标准 :map iterator returns badptr on find

转载 作者:行者123 更新时间:2023-11-28 01:07:02 25 4
gpt4 key购买 nike

我的 std::map 定义为

typedef std::map<string,ImageData*> ImageDataMap;
typedef std::pair<string,ImageData*> ImageDataPair;
typedef std::map<string,ImageData*>::iterator ImageDataIterator;

上面的 map 存储了作为图像文件名的字符串和作为图像元数据的 ImageData。当我使用如下所示的查找时

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

iter->first 是一个 badptr,因此它无法满足下面的 if 条件。这里出了什么问题?在xp64上运行vc9 express edition(程序是32bit的)

最佳答案

map::find()map::end 形式返回的迭代器意味着在容器中找不到指定的键。您不能取消引用它来访问它的元素。它会使您的应用程序崩溃。

编辑:

让我们说清楚。问题是你在颠倒逻辑,好吗?您只能使用有效的迭代器,因此 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比较:if (iter == imageMap->end()) 这意味着执行下面的 block 如果我搜索的元素不在 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;
}

关于c++ - 标准 :map iterator returns badptr on find,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5519730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com