我正在尝试使用一个字符串作为 std::map 的键,因为该字符串可以从程序的不同部分更改,但我遇到一个问题,我可以轻松地将数据存储在 map 中,但我不能访问它是因为它要求指针地址作为键,我想从字符串的值访问该数据。
这是代码
using namespace std;
string *AString = "pointer";
map<string *, bool> AMap; //Declare
AMap[AString] = true; //Insert into map with key AString
cerr << AMap["pointer"]; //Does not work
最佳答案
解决方案是不使用指针:
using namespace std;
string AString = "pointer";
map<string, bool> AMap;
AMap[AString] = true;
cerr << AMap["pointer"];
本地图键位于 map 中时,您真的不希望它被程序的其他部分更改。这只是自找麻烦,表明存在设计问题。
关于c++ - 访问以指针类型为键的 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648061/