4
How do I vector/array integer numbers with strings as index?
Something that in Lua 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 serve.
4
How do I vector/array integer numbers with strings as index?
Something that in Lua 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 serve.
8
Possibly PHP addiction right, I’ve been there, I think the solution closest 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;
}
2
In C is not possible (I do not know C++).
In C the indices of arrays are obligatory integers.
What you can do is convert the string to a (single) number and use that number as input 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 choosing the function hash()
.
There are libraries already made that facilitate this process.
Know if BOOST has any (library)?
see example in ideone: http://ideone.com/9nyS18
Gabriel, I don’t know BOOST.
@pmg as you showed yourself is possible yes. You will not have syntactic ease. You can do it in other ways than yours as well. They’ll all look a little ugly but it’s possible. Boost is C++ library. Much of what exists in Boost has a similar shape in the standard C++ library in newer versions.
Browser other questions tagged c++
You are not signed in. Login or sign up in order to post.
Served perfectly.
– Gabriel Sales