Search code examples
c++vectoraddressing

Using char to access vector<int>


I'm working my way through the leetcode problems in C++ for practice.

I'm at problem number 3. I don't quite understand why you can access vector using char datatype.

For example:

vector<int> chars(128);
char c = 'a';
chars[c]++;

The above code just means increment the vector at position 'a'??? by 1.

I'm confused. Are we not suppose to access vectors like an array using numerical index?

Does vectors implicitly convert char types to decimal?

Some clarification would be appreciated.


Solution

  • Assuming your system is using ASCII or UTF-8 or something like that, 'a' == 97.

    So, this is equivalent to chars[97]++.