key from std::map won't be passed to function parameter

Viewed 41

I am writing c functions to c++ std::map. One of those functions, getKey, tries to get a certain key from an object of std::map and passes it to a parameter in order to be used later.

but after function call, the parameter does not have anything in it.

I could not figure out why. Any advice would be highly appreciated.

#include <iostream>
#include <map>
#include <string>

using hashtable_t = std::map<std::string, int64_t>;

hashtable_t* initializeTable()
{
    return new hashtable_t();
}

size_t getTableSize(hashtable_t* table)
{
    return table->size();
}

bool addTableEntry(hashtable_t* table, const char* key, int64_t value)
{
    // std::cout << "key: " << key << " value: " << value << std::endl;
    const auto [iter, success] = table->insert(std::pair(key, value));
    return success;
}

size_t getKey(hashtable_t* table, int64_t seq, char* key)
{
    int64_t i=0;
    for(auto iter=table->begin(); iter!=table->end(); ++iter)
    {
        if (i == seq)
        {
            key = iter->first;
            return iter->first.size();
        }
        ++i;
    }
    return 0;
}

void destroyTable(hashtable_t* table)
{
    delete table;
}

int main()
{
    bool success;
    size_t size;
    int64_t value;
    size_t length;

    hashtable_t* table = initializeTable();

    success = addTableEntry(table, "aaa", 111);
    success = addTableEntry(table, "bbb", 222);
    success = addTableEntry(table, "ccc", 485);


    size = getTableSize(table);
    std::cout << "Size: " << size << std::endl;

    for(int i=0; i<size; ++i)
    {
        char* key = nullptr;
        length = getKey(table, i, key);
        std::cout << "length: " << length << " key: " << key << std::endl;
    }


    destroyTable(table);
    return 0;
}

1 Answers

Your key is a std::string so change getKey to return a std::string.

std::string getKey(hashtable_t* table, int64_t seq)
{
    int64_t i=0;
    for(auto iter=table->begin(); iter!=table->end(); ++iter)
    {
        if (i == seq)
        {
            return iter->first;
        }
        ++i;
    }
    return std::string();
}

then

std::string key = getKey(table, i);

There's a few things about your code that are strange. It's not clear why you are using a map, you aren't doing anything with it that couldn't be done more efficiently with a vector. It's also pointless to dynamically allocate the map, when you then delete it exactly as if it was a stack variable. If you want your map to have the lifetime of a stack variable, then a stack variable is what you should use.

Related