MST

星途 面试题库

面试题:C++ 中使用 find 进行多条件查找基础应用

假设有一个 std::vector<int> 容器,里面存储了一系列整数。请使用 C++ STL 中的 find 算法,在这个容器中查找既大于5又小于10的第一个元素,并返回其迭代器。请写出完整的代码实现。
11.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

int main() {
    std::vector<int> vec = {1, 3, 7, 12, 8, 5};

    auto it = std::find_if(vec.begin(), vec.end(), [](int num) {
        return num > 5 && num < 10;
    });

    if (it != vec.end()) {
        std::cout << "找到元素: " << *it << std::endl;
    } else {
        std::cout << "未找到符合条件的元素" << std::endl;
    }

    return 0;
}