首页 > 解决方案 > 这个哈希表中的“:”和“ch”是什么意思循环“for(char ch:key)”?

问题描述

我知道这可能不仅适用于哈希表,而且关于它的答案将帮助我更好地理解它:

int hash (const string & key, int tableSize) {
    int hashVal = 0;
    for (char ch : key) // ????lost here??? is ch is just any character in the key???
        hashVal += ch;
    return hashVal % tableSize;
}

标签: c++for-loop

解决方案


字符串被认为是字符的集合。

解释:对于字符串中的每个字符key,执行循环体。

ch : key

  • ch是一个循环变量的名称,它会从名为 key 的字符串中一次分配一个字符,并且循环体将使用该值ch迭代地执行
  • :这将循环变量与字符串分隔开来。

参见“基于范围的 for 循环”(C++11 起)


推荐阅读