How to Vector/Array integers indexed by strings?

Asked

Viewed 775 times

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.

2 answers

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.

  • 2

    @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

You are not signed in. Login or sign up in order to post.