面试题答案
一键面试在C++ STL中,std::vector<int>
的end
迭代器指向容器中最后一个元素的下一个位置。在使用迭代器遍历std::vector<int>
时,我们使用begin
获取起始迭代器,通过与end
迭代器比较来判断是否遍历结束,这样能确保不会越界。
以下是代码示例:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 获取起始迭代器
auto it = vec.begin();
// 使用end迭代器进行区间判断
while (it != vec.end()) {
std::cout << *it << " ";
++it;
}
return 0;
}
在上述代码中,while (it != vec.end())
确保了迭代器 it
在到达 vec.end()
之前持续循环,从而正确遍历std::vector<int>
且不会越界。当it
等于vec.end()
时,说明已经遍历完容器内所有元素。