MST

星途 面试题库

面试题:C++ 中容器与泛型算法结合应用问题

假设有一个 `std::vector<int>` 容器,里面存储了一些整数。要求使用泛型算法对其进行排序,并且在排序后使用泛型算法找出第一个大于10的元素,并返回其位置。请写出对应的C++ 代码。
44.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

int main() {
    std::vector<int> vec = {5, 15, 8, 20, 3};

    std::sort(vec.begin(), vec.end());

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

    if (it != vec.end()) {
        std::cout << "第一个大于10的元素位置是: " << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << "没有找到大于10的元素" << std::endl;
    }

    return 0;
}