我对C++地图有个奇怪的问题。
首先,我插入文件名作为key,一个递增的整数作为value:
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()与文件映射中的某个键相同,但在映射中找不到它。
相反,如果我更改了将元素插入到map中的方式,如下所示(其余内容相同):
...
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“。
我调试了很长一段时间,但仍然不能解决它。任何帮助都是非常感谢的。
发布于 2012-11-25 05:46:27
为了将const char*用作map的键,您需要提供一个比较器。请参阅Using char* as a key in std::map
一个更简单的选择是更改贴图以使用std::string作为其关键点。
https://stackoverflow.com/questions/13545928
复制相似问题