lundi 30 octobre 2017

convert map

I am trying to cast a map pointer to void * with reinterpret_cast and then cast it back using static_cast

Right now i have a problem trying to get the values stored in the map after casting the void * back to map<string, int> *

I tried with both a range based loop and with an iterator but i can't seem to find a way to get the keys, every time i try to access the map values i get a segmentation fault.

This is a small example of the code i have:

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);

I need to find a way, if possible, to retrieve the keys of the map to get the values back from it.
Right now i don't know if the problem leading to the segmentation fault is in the casting to void * and back or the error occurs when i was trying to get the keys back with the iterator or the loop.

Aucun commentaire:

Enregistrer un commentaire