C++ vector 遍历:迭代器与下标方法详解
C++ 中的 vector 可以使用迭代器或者下标来遍历,具体方法如下:
- 使用迭代器遍历
vector<int> vec{1, 2, 3, 4, 5};
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << ' ';
}
- 使用下标遍历
vector<int> vec{1, 2, 3, 4, 5};
for (int i = 0; i < vec.size(); ++i) {
cout << vec[i] << ' ';
}
注意:使用下标遍历需要注意边界问题,不要越界。而使用迭代器遍历则不需要考虑这个问题。
原文地址: https://www.cveoy.top/t/topic/m1q7 著作权归作者所有。请勿转载和采集!