前情提要
本篇作为c++教程,1.4-变量的使用,其中const限定符部分的补充。由于关于迭代器的内容并不适合被放置于入门教程的开始部分,因此单独拿出来新开一个篇章。
另外,在了解迭代器使用const限定以前,至少应该先掌握指针使用const限定。
STL使用迭代器
stl中的迭代器类似于指针,以vector<int>类型为例,使用迭代器需要使用vector<int>::iterator
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v = {1, 2, 3, 4, 5};
// 使用vector<int>::iterator创建一个迭代器
vector<int>::iterator it = v.begin();
cout << *it << endl;
return 0;
}
当然,在c++11中,如果你要使用一个迭代器,不必再直接写出vector<int>::iterator了,可以直接使用auto进行声明。