MST

星途 面试题库

面试题:C++ 中find算法查找范围的基本应用

给定一个C++ 的std::vector<int> 容器,里面包含若干整数。使用C++ STL中的find算法,查找从容器第3个元素(索引为2)开始到倒数第2个元素之间是否存在值为10的元素,若存在则输出其索引位置,若不存在输出 -1 ,请写出完整代码。
38.5万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

int main() {
    std::vector<int> vec = {1, 2, 10, 4, 5, 10, 7};
    auto it = std::find(vec.begin() + 2, vec.end() - 1, 10);
    if (it != vec.end() - 1) {
        std::cout << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << -1 << std::endl;
    }
    return 0;
}