MST

星途 面试题库

面试题:C++ STL 迭代器 begin 的反向迭代运用之复杂场景

假设有一个自定义类MyClass,包含两个int类型成员变量a和b,将若干MyClass对象放入std::list<MyClass> 容器中。现在需要使用rbegin反向迭代器遍历这个列表,并找出满足a > b条件的第一个对象,然后输出该对象的a和b值。请实现相关的代码,包括类的定义、容器的填充以及迭代查找的过程。
16.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

class MyClass {
public:
    int a;
    int b;
};

int main() {
    std::list<MyClass> myList;

    // 填充容器
    MyClass obj1 = {3, 2};
    MyClass obj2 = {1, 4};
    MyClass obj3 = {5, 3};
    myList.push_back(obj1);
    myList.push_back(obj2);
    myList.push_back(obj3);

    auto it = myList.rbegin();
    while (it != myList.rend()) {
        if (it->a > it->b) {
            std::cout << "找到满足条件的对象, a = " << it->a << ", b = " << it->b << std::endl;
            break;
        }
        ++it;
    }

    if (it == myList.rend()) {
        std::cout << "未找到满足条件的对象" << std::endl;
    }

    return 0;
}