简体   繁体   English

使用 char 访问向量<int></int>

[英]Using char to access vector<int>

I'm working my way through the leetcode problems in C++ for practice.我正在通过 C++ 中的 leetcode 问题进行练习。

I'm at problem number 3. I don't quite understand why you can access vector using char datatype.我遇到了第 3 个问题。我不太明白为什么可以使用char数据类型访问向量。

For example:例如:

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

The above code just means increment the vector at position 'a' ???上面的代码只是意味着在 position 'a'处增加向量? by 1.由 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?向量是否将 char 类型隐式转换为十进制?

Some clarification would be appreciated.一些澄清将不胜感激。

Assuming your system is using ASCII or UTF-8 or something like that, 'a' == 97 .假设您的系统使用 ASCII 或 UTF-8 或类似的东西, 'a' == 97

So, this is equivalent to chars[97]++ .所以,这相当于chars[97]++

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.应该像 arrays 一样访问向量。 There are std::vector<>::operator[] and std::vector<>::at() for this为此有std::vector<>::operator[]std::vector<>::at()

Does vectors implicitly convert char types to decimal?向量是否将 char 类型隐式转换为十进制?

There's no "decimal" type in C++. C++ 中没有“十进制”类型。 And std::vector doesn't do anything in this case.在这种情况下, std::vector不会做任何事情。 operator[] receives a size_type , and char is implicitly convertible to size_type , so C++ will convert c to the appropriate type. operator[]接收size_type ,并且char可以隐式转换为size_type ,因此 C++ 会将c转换为适当的类型。 char is not meant for storing characters. char不是用来存储字符的。 It's just a numeric type like int or long .它只是一个像intlong这样的数字类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM