c++ - 什么是++array[str[i]];做?

标签 c++ arrays

我找到了一个程序,可以打印出char数组中出现次数最多的字符。 这是代码。

void main()
{

    int array[255] = {0}; // initialize all elements to 0

    char str[] = "thequickbrownfoxjumpedoverthelazydog";

    int i, max, index;

    for(i = 0; str[i] != 0; i++)
    {
        ++array[str[i]];
    }

    // then find the most used charater ...
}

我不太明白 ++array[str[i]]; 的作用。

我们将数组初始化为 int array[255] 但它仍然接受索引作为 str[i] 我认为是 char 类型.

是不是str[i]自动转成ASCII?命令前面的 ++ 有什么作用?

最佳答案

在这段代码中

++array[str[i]];

i 遍历 str 的长度(因为我们在里面设置了循环...)。

对于 str 中的每个字符,表达式 str[i] 获取该字符的值。我使用“值”而不是“字符”,因为它后来被视为整数索引。

使用该值,表达式 array[str[i]] 访问数组中的一项。该数组中的每个条目对应一个可能的 ASCII“字符”。

++ 增加数组中的值。 IE。它计算例如出现的次数'一个'。

总的来说,代码在 str 中制作了一个 ASCII 字符频率的直方图。

但是请注意 WhozCraig 的重要警告,以防您打算使用它。您必须符合代码所做的假设(为完整起见,经许可复制):

Just fyi, not casting that index to unsigned char is a recipe for disaster. Further, this is not using a table guaranteed to hold enough slots to cover the domain. i.e. 1 << CHAR_BIT in width. It will "work" (term used loosely) for your input string presented here. It is not an end-all general solution to char counting.

关于c++ - 什么是++array[str[i]];做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58889076/

相关文章:

javascript - 使用Lodash过滤2个集合

ruby - 生成一组 float 会产生奇怪的结果

c++ - Windows 8.1 上的最小编译环境

java - Java 与 C++ 中随机数生成实现的时间差异

c++成员函数模板专门化类非类型模板参数

javascript - fetch:将项目推送到数组

ios - Swift - URL 数组不起作用

c++ - OpenMP - 通过单个线程访问单个文件

c++ - 可移植 VFS 库 C++

c - C 中的多维数组出现错误