How do I make a vector / array of integers with strings as index?
Something on the Moon would be:
vetor = {
["eu"] = 10,
["voce"] = 11,
}
ps: It will be dynamic, so it will not have a fixed size. ps²: Struct or enum do not work.
How do I make a vector / array of integers with strings as index?
Something on the Moon would be:
vetor = {
["eu"] = 10,
["voce"] = 11,
}
ps: It will be dynamic, so it will not have a fixed size. ps²: Struct or enum do not work.
Possibly a PHP bug, I've been through this, I think the closest solution to this is std: map
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map <std::string, int> data{
{ "Maria", 10 },
{ "Joao", 15 },
{ "Anabelo", 34 },
{ "Fulaninho", 22 },
};
for (const auto& element : data)
{
std::cout << "Chave(key = first): " << element.first;
std::cout << "Valor(value = second): " << element.second << '\n';
}
return 0;
}
In C it's not possible (I do not know C ++).
In C the array indices are necessarily integers.
What you can do is to convert the string to a unique number and use that number as the index for the array (operation commonly known as hashing ).
#include <stdio.h>
/* esta função de hash() e muito basica. NAO USAR! */
int hash(const char *index) {
return *index == 'e';
}
int main(void) {
int vetor[2] = {11, 10};
printf("eu ==> %d\n", vetor[hash("eu")]);
printf("voce ==> %d\n", vetor[hash("voce")]);
return 0;
}
The trick is in the choice of the function hash()
.
There are already libraries that have made this process easier.