我正在尝试将 map 指针转换到 void *
与 reinterpret_cast
然后使用 static_cast
将其投回
现在我在尝试获取映射中存储的值时遇到了问题 void *
返回map<string, int> *
我尝试使用基于范围的循环和迭代器,但我似乎无法找到获取键的方法,每次我尝试访问映射值时都会出现段错误。
这是我的代码的一个小例子:
auto *map_pointer = new map<string, int>;
for (const auto &entry : array){
if (map_pointer->find(entry) == map_pointer->end()) {
map_pointer->at(entry) = 1;
} else {
map_pointer->at(entry)++;
}
}
void *test = reinterpret_cast<void *>(map_pointer);
auto foo = static_cast<std::map<std::string, int> *>(test);
如果可能的话,我需要找到一种方法来检索 map 的键以从中取回值。
现在我不知道导致段错误的问题是否在转换为 void *
时然后返回,或者当我试图用迭代器或循环取回 key 时发生错误。
最佳答案
- 关于指针转换 - 正如 StoryTeller 指出的那样 - 您可以将 map 指针分配给
void*
并在需要时返回static_cast
。 - 关于段错误,您为映射中未找到的键调用
at
,这导致std::out_of_range
您更正后的代码可能类似于以下内容:
std::map<int, int> m = {{0, 8}, {1, 9}, {2, 32}};
std::vector<int> arr = {0, 3, 2};
for (const auto &entry : arr){
if (m.find(entry) == m.end()) {
m.insert({entry, 1});
} else {
m[entry]++;
}
}
void *mp = &m;
std::map<int, int> *m2 = static_cast<std::map<int, int>*>(mp);
for (const auto& i : *m2) {
std::cout << i.first << ":" << i.second << "\n";
}
打印 0:9 1:9 2:33 3:1
。参见 demo on coliru
关于c++ - 将 map<string, int> 转换为 void* 并返回并获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47018498/