Unordered_map 找到常量 wchar_t*
Unordered_map find const wchar_t*
我使用以下代码从文件路径获取文件名:
const wchar_t* MyClass::PathFindFileNameW(const wchar_t* path)
{
const wchar_t* p1 = path ? wcsrchr(path, L'\') : nullptr;
const wchar_t* p2 = path ? wcsrchr(path, L'/') : nullptr;
p1 = !p1 || (p2 && p2 > p1) ? p2 : p1;
return (p1 ? p1 + 1 : path);
}
我还有如下unordered_map定义:
std::unordered_map<const wchar_t*,std::string> mymap = {
{L"file1.doc","Author1"},
{L"file2.doc","Author2"},
{L"file3.doc","Author3"} };
使用以下代码,我想通过文件名从地图中获取作者:
std::unordered_map<const wchar_t*,std::string>::const_iterator got = mymap.find(this->PathFindFileNameW(this->path));
if (got == mymap.end())
{
Log("No result");
}
即使文件名存在于地图中,此代码也会记录“无结果”。类似于:
std::unordered_map<const wchar_t*,std::string>::const_iterator got = mymap.find(L"file1.doc");
给出结果。我在这里错过了什么?
你有一个以指针作为键的映射,所以你只能找到一个字符串,如果它存储在与键相同的地址。
使用std::wstring
作为键。
我使用以下代码从文件路径获取文件名:
const wchar_t* MyClass::PathFindFileNameW(const wchar_t* path)
{
const wchar_t* p1 = path ? wcsrchr(path, L'\') : nullptr;
const wchar_t* p2 = path ? wcsrchr(path, L'/') : nullptr;
p1 = !p1 || (p2 && p2 > p1) ? p2 : p1;
return (p1 ? p1 + 1 : path);
}
我还有如下unordered_map定义:
std::unordered_map<const wchar_t*,std::string> mymap = {
{L"file1.doc","Author1"},
{L"file2.doc","Author2"},
{L"file3.doc","Author3"} };
使用以下代码,我想通过文件名从地图中获取作者:
std::unordered_map<const wchar_t*,std::string>::const_iterator got = mymap.find(this->PathFindFileNameW(this->path));
if (got == mymap.end())
{
Log("No result");
}
即使文件名存在于地图中,此代码也会记录“无结果”。类似于:
std::unordered_map<const wchar_t*,std::string>::const_iterator got = mymap.find(L"file1.doc");
给出结果。我在这里错过了什么?
你有一个以指针作为键的映射,所以你只能找到一个字符串,如果它存储在与键相同的地址。
使用std::wstring
作为键。