小编dis*_*ery的帖子

C++ 中的迭代器究竟是什么?

我试图掌握迭代器的概念。我通过以下代码运行了一些测试:

#include <iostream>
#include<map>
using namespace std;

int main(){
    map<string,string> mp;//create the map
    mp["key"]="value";//create a key/val pair

    map<string,string>::iterator it=mp.begin();//create an iterator named it


    cout<<(&it)<<" "<<(&*it)<<endl;// 0x7ffeeccd6a18 0x7f9dc5c05970
    it++;//moving the current value of the iterator
    cout<<(&it)<<" "<<(&*it);// 0x7ffeeccd6a18 0x7ffeeccd6a70
}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,我们可以将迭代器概念化为一个包含值的盒子——我们正在迭代的可迭代对象的值。当我们做“it++”时;并移动迭代器的当前值,我们现在正在访问不同的元素,这就是 (&*it) 更改的原因。实际的框不会改变,这就是为什么 (&it) 在两种情况下都保持不变(因为我们正在获取迭代器对象的地址)。

我不确定我是否理解正确,所以请告诉我是否正确,如果我错了请纠正我。

c++ pointers iterator

2
推荐指数
1
解决办法
94
查看次数

标签 统计

c++ ×1

iterator ×1

pointers ×1