c++ - 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
?当地图获得第二个元素时会发生这种情况。
解决方案
您只存储指向地图first.data()
和second.data()
地图的指针。如果它们中的任何一个重新定位字符串数据,则指针会悬空,并且如果您尝试取消引用它们,则会出现 UB(未定义行为)。如果它们不重新定位,您将拥有指向内存中完全相同的字符串的指针。如果地图过期first
和/或second
地图中的指针再次变得悬空并且取消引用它们将再次导致 UB。
相反,将std::wstring
s 存储在地图中:
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
推荐阅读
- python - 如何在一张图像中隐藏两种不同格式的消息并在解码后以相同格式检索?
- ruby-on-rails - Solargraph 已经初始化了常量 Bundler
- php - Laravel 关系有很多
- skyve - 带有服务器操作的 Skyve 非持久主页进入无限循环
- python - 在 python-telegram-bot 中查找 chat_id
- reactjs - 如何使用 antd 选项卡动态显示/隐藏按钮
- ios - 如何在鼠标拖动时将绘制的形状绑定为正方形
- python - 如何将数据框转换为字典
- c# - 在 SQL 数据库中进行手动更改时,Lucene.Net 索引更新
- angular - 在 Angular 上将文档作为经过身份验证的用户存储在 Firestore 中