在映射中,键值对不存储在传染性内存中,因此迭代器如何使用它++从一个键值对跳转到另一个键值对

问题描述

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
  map<string,int> map1;

  map1["ank"] = 12;
  map1["ghan"] = 13;
  map<string,int>::iterator iter;

  for (iter = map1.begin(); iter != map1.end(); iter++)
  {
    cout << (*iter).first << " " << (*iter).second << endl;
    /* code */
  }

  return 0;
}

查询

  1. 我想问一下,如何通过使用 it++ 来遍历整个地图,因为它们不在传染性内存中
  2. 为什么不让它起作用+1。

解决方法

确切的机制取决于实现,但最常见的实现将在每个键/值对旁边使用一对指针。

这是一对指针,因此您也可以调用 it--。但是由于您只有两个指针,因此您不能执行 +3+17。拥有一个只能做 +N

+1 并没有什么用 ,

std::mapcommonly implemented 作为 red-black tree,其中每个节点都有指向一些周围节点的指针。 map 的迭代器被简单地实现为通过遵循这些指针链从一个节点到另一个节点迭代该树。