Using char to access vector<int>

868 Views Asked by At

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.

2

There are 2 best solutions below

4
Bill Lynch On BEST ANSWER

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

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

1
phuclv On

Are we not suppose to access vectors like an array using numerical index?

Who told you that? Vectors are supposed to be accessed exactly like arrays. There are std::vector<>::operator[] and std::vector<>::at() for this

Does vectors implicitly convert char types to decimal?

There's no "decimal" type in C++. And std::vector doesn't do anything in this case. operator[] receives a size_type, and char is implicitly convertible to size_type, so C++ will convert c to the appropriate type. char is not meant for storing characters. It's just a numeric type like int or long.