Do you have any way to access a position using a string?

1

Would not I have some way to access a position using a string ? Example:

int vetor[1000000];

vetor["abc"]++;

I know it's crazy, but ... "abc" = 01100001, 01100010, 01100011, 00000000 (null character), so "abc" should not represent 1633837824?

    
asked by anonymous 07.08.2016 / 23:16

1 answer

2

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

Aside from the fact that in this case you would get a location in memory that does not belong to the declared array , you can do this:

#include <iostream>
using namespace std;

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

See working on ideone .

    
07.08.2016 / 23:38