1
我對C++映射有一個奇怪的問題。在C++映射中找不到元素
首先我插入文件名作爲重點,越來越整數值:
int getdir (const char* dir, map<const char*, int> &filemap)
{
DIR *dp;
struct dirent *dirp;
if((dp = opendir(dir)) == NULL)
{
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
int index = 0;
while ((dirp = readdir(dp)) != NULL)
{
string temp1(dir);
string temp2(dirp->d_name);
if(!isalpha(temp2[0]))
{
continue;
}
filemap[dirp->d_name] = index;
index++;
}
closedir(dp);
return 0;
}
然後在另一個功能,我想看看這個地圖找如果下面的代碼片段存在一定的文件名:
stringstream ss(firststr);
string sourceid;
getline(ss, sourceid, ':');
sourceid = sourceid+".txt";
if(filemap.find(sourceid.c_str())!=filemap.end())
{
cout<<"found"<<endl;
}
我檢查過sourceid.c_str()與filemap中的某個鍵相同,但它不會在地圖中找到。
相反,如果我改變插入元件插入地圖以下的方式(其餘是相同的):
...
string temp1(dir);
string temp2(dirp->d_name);
...
filemap[temp2.c_str()] = index; //previously is filemap[dirp->d_name] = index;
index++;
然後某個鍵可以在其他功能的地圖找到。然而,問題是文件映射只包含最後一個元素,其大小爲1.似乎映射的關鍵字被覆蓋,因此映射最後包含「last_element => last_index」。
我已經調試了很久,但仍然無法解決它。任何幫助表示讚賞。
好吧,讓我試試看。 – Iam619
是的..它工作......但爲什麼不能使用const char *?我很高興它解決得如此之快而且很難過,我花了很長時間沒有試圖將它改變爲絃樂......非常感謝。 – Iam619
簡而言之,您需要提供一個比較器來使'std :: map'按預期工作。如果沒有比較器,'map.find()'會比較指針而不是比較實際的字符串。看到http://stackoverflow.com/questions/4157687/using-char-as-a-key-in-stdmap –
NPE