MST

星途 面试题库

面试题:C++ STL 迭代器 begin 的反向迭代运用之基础实践

给定一个C++的std::vector<int> 容器,如何使用begin的反向迭代器(即rbegin)来遍历这个容器并输出其中元素,要求从最后一个元素开始输出到第一个元素,同时需要考虑如何处理容器为空的情况。请写出完整代码。
33.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec;
    // 这里可以添加初始化元素的代码,例如:
    // vec = {1, 2, 3, 4, 5}; 

    if (vec.empty()) {
        std::cout << "容器为空" << std::endl;
    } else {
        for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
            std::cout << *it << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}