首页 > 解决方案 > Unordered_map 奇怪的字符

问题描述

    std::wifstream ifs("debug.txt");

    std::wstring s;
    std::unordered_map <LPTSTR, LPTSTR> x;
    std::wstring delimiter = L"|";
    size_t pos = 0;
    std::wstring first;  
    std::wstring second;

    while (std::getline(ifs, s)) {   

        pos = s.find(delimiter);
        first = s.substr(0, pos);
        second = s.substr(pos + 1, std::string::npos );

        x[first.data()] = second.data();
    }

    return x;

为什么在x存储一些奇怪的字符return x?当地图获得第二个元素时会发生这种情况。

在此处输入图像描述

标签: c++

解决方案


您只存储指向地图first.data()second.data()地图的指针。如果它们中的任何一个重新定位字符串数据,则指针会悬空,并且如果您尝试取消引用它们,则会出现 UB(未定义行为)。如果它们不重新定位,您将拥有指向内存中完全相同的字符串的指针。如果地图过期first和/或second地图中的指针再次变得悬空并且取消引用它们将再次导致 UB。

相反,将std::wstrings 存储在地图中:

std::unordered_map <std::wstring, std::wstring> x;

// ...

x[first] = second;        // replaces the value, second, if first already exists

// or

x.emplace(first, second); // do not replace value if first already exists

推荐阅读