使用数组索引 C++ 声明 std::list

Declaring a std::list with an array index C++

当我观察到视频作者使用数组索引初始化 std::list 时,我正在在线关注哈希 table 实现 (https://www.youtube.com/watch?v=2_3fR-k-LzI)。这让我很困惑,因为我一直认为 std::list 总是像链表一样运行,并且不能支持随机索引。但是,我认为这可能是一种声明列表大小的奇怪方式,因此忽略了它并继续前进。具体来说,他做了以下事情:

static const int hashGroups = 10;
std::list<std::pair<int, std::string>> table[hashGroups];

在尝试实现一个函数来搜索以查看散列 table 中是否存在键时,我意识到我无法访问 std::list 对象,正如我所期望的那样.在 HashTable.cpp (其中包括定义上述两个变量的头文件)中,我只能使用 -> 而不是 with 来访问 table 成员变量的元素作为指针。正如我所期望的那样。看起来直接导致这种情况的原因是在列表定义中使用了数组索引。这似乎将 table 变量的类型从 std::list 更改为指向 std::list 的指针。我不明白为什么会这样。这似乎也打破了我当前尝试遍历 table 变量的实现,因为当我声明一个迭代器来遍历 table 的元素时,我能够看到 table在 VS 调试器中有正确的数据,但迭代器似乎有完全无效的数据,并且即使看到 table 正确地有 10 个元素,也不会迭代循环一次。下面粘贴我对搜索功能的尝试:

std::string HashTable::searchTable(int key) {
   for (std::list<std::pair<int, std::string>>::const_iterator it = table->begin(); it != table->end(); it++)
   {
      if (key == it->first) {
         return it->second;
      }
      std::cout << "One iteration performed." << std::endl;
   }
   return "No value found for that key.";
}

综上所述,我有几个亟待解决的问题:

  1. 当 std::list 不支持随机访问时,为什么我们甚至可以用括号声明列表?
  2. 为什么像这样声明列表会将列表的类型从 std::list 更改为指针?
  3. 在其当前实现中使用迭代器迭代 table 的正确方法是什么?

感谢您提供的任何帮助或见解!

阅读@IgorTandetnik 的回复后,我意识到我对列表的看法是错误的。我没有完全理解的是,我们正在声明一个列表数组,而不是试图像数组一样初始化一个列表。一旦我意识到这一点,我就能够正确地访问元素,因为我没有尝试使用列表的迭代器来遍历数组。据我所知,我修改后的 searchTable 函数现在可以正常工作,如下所示:

std::string HashTable::searchTable(int key) {
   int hashedKey = hashFunction(key);

      if (table[hashedKey].size() > 0)
      {
         for (std::list<std::pair<int, std::string>>::const_iterator it = table[hashedKey].begin(); it != table[hashedKey].end(); it++)
         {
            if (key == it->first) {
               return it->second;
            }
         }
   }
   return "No value found for that key.";
}

并回答我之前的三个问题...

  • 1。当 std::list 不支持随机访问时,为什么我们甚至可以声明一个带括号的列表?
    • 响应:我们正在声明一个 std::list 的数组,其中包含一个 std::pair 的 int 和 std::string,而不是一个带有数组索引运算符的列表。
  • 2。为什么像这样声明一个列表会将列表的类型从 std::list 更改为指针?
    • 响应:因为我们将 table 声明为一个数组(相当于指向第一个元素的 const 指针),其中 包含 个实例 std::list.所以我们永远不会“改变”列表变量的类型。
  • 3。在其当前实现中使用迭代器迭代 table 的正确方法是什么?
    • 响应:当前实现仅尝试迭代 table 的第一个元素。创建一个迭代器,它使用散列键值作为 table 的数组索引,然后尝试遍历 std::list 在该索引处保存 std::pair 的实例。