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