0

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.

phuclv
  • 37,963
  • 15
  • 156
  • 475
diggledoot
  • 691
  • 8
  • 22
  • Because `char` is an integral type, just as `int`, `unsigned`, `long`, etc are. All integral types are implicitly convertable to the unsigned integral type (typically `std::size_t`) used for indexing in standard containers, like `std::vector`. Bear in mind that the value of `char` literals (like `'a'`) is implementation defined, but is not zero or one in any standardised character set (e.g. it has value `97` in character sets compatible with ASCII) and accessing container elements with an out-of-range index gives undefined behaviour. – Peter Jun 06 '21 at 03:46

2 Answers2

1

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

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

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • So implicitly, if I supply the char 'a' to [] in the vector, it will convert it to its decimal form in ASCII? – diggledoot Jun 06 '21 at 03:25
  • @cswannabe: Yeah. – Bill Lynch Jun 06 '21 at 03:25
  • "So implicitly, if I supply the char 'a' to [] in the vector, it will convert it to its decimal form in ASCII?" No. When you provide `c = 'a';` you tell compiler "on my system assign 97 to c". On different platform that does not use ASCII that number could be different. There are no decimals in computer memory, no symbols, only numbers and it is how you interpret numbers. – Slava Jun 06 '21 at 03:37
  • It is implementation-defined whether an implementation (compiler and standard library) will use an ASCII (or compatible) character set. – Peter Jun 06 '21 at 03:48
1

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.

phuclv
  • 37,963
  • 15
  • 156
  • 475