c++ - 将 map<string, int> 转换为 void* 并返回并获取 key

标签 c++ c++11 pointers void-pointers

我正在尝试将 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/

相关文章:

c++ - 使用 winsock 解析 DNS,服务器位于路由器后面

c++ - 错误 LNK2005 : "class Player m_player" already defined in Game. 对象

windows - DirectX 11 视频播放

c++ - 候选模板被忽略 : substitution failure(error with clang but not g++)

C++:ostream << 运算符错误

c - 在 C 中使用 strtok 将日期字符串转换为整数

c++ - 错误 : expected unqualified-id before '&' token

c++ - 将 Sublime Text 与 cmake(构建系统)结合使用

C++:我可以使用指针超出应用程序内存的范围吗?

c - 如何找到数组的大小(从指向数组第一个元素的指针)?