一、四种迭代器
拿vector举例
- 非const对象的正向迭代器
vector<int>::iterator it = v.begin();
while (it != v.end()) {
cout << *it << " ";
it++;
}
- 非const对象的反向迭代器
vector<int>::reverse_iterator rit = v.rbegin();
while (rit != v.rend()) {
cout << *rit << " ";
++rit;
}
- const对象的正向迭代器与const对象的反向迭代器
void print_vector(const vector<int>& v) {//在实际过程中一般不直接使用const 定义对象
//一般和引用&用于传参中,引用提高效率,const防止改变对象
//const对象的正向迭代
vector<int>::const_iterator it = v.begin();
while (it != v.end()) {
cout << *it << " ";
++it;
}
cout << endl;
//const对象的反向迭代
vector<int>::const_reverse_iterator rit = v.rbegin();
while (rit != v.rend()) {
cout << *rit << " ";
rit++;
}
cout << endl;
}
二、三种遍历方法
- for+下标遍历
for (size_t i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
- for+auto遍历
for (auto e : v) {//也可以写成auto& e可修改v里的内容
cout << e << " ";
}
cout << endl;
- 迭代器遍历
vector<int>::iterator it = v.begin();//也可以写成auto it=vbegin();更加简洁
while (it != v.end()) {
cout << *it << " ";
++it;
}
cout << endl;