Is there any way to access a position by string?

Asked

Viewed 133 times

1

There would be no way to access a position using a string? Example:

int vetor[1000000];

vetor["abc"]++;

I know it’s crazy of me, but... "abc" = 01100001, 01100010, 01100011, 00000000 (null character), so "abc" shouldn’t represent 1633837824?

  • Only do map<string, int> seuMap; seuMap["abc"] = 0; etc... http://www.cplusplus.com/reference/map/map/

1 answer

2


It is possible through a map or unordered_map, where the index can be purposefully a string. But where an integer value is expected it cannot use an string, at most can be used some conversion algorithm of string (can be a cast) for an integer that makes sense for use as an index. So yes, it is "crazy" to think that a text could be used directly in an index of a array.

Apart from the fact that in this case it would take a memory site that does not belong to the array declared, can do this:

#include <iostream>
using namespace std;

int main() {
    int vetor[100000];
    vetor[(int)"a"] = 1; // é 0110000100000000
    cout << vetor[(int)"a"];
}

I put in the Github for future reference.

  • Thanks! I was wanting something different from the map because it is a little slower than a vector, but thanks :D

Browser other questions tagged

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