MST

星途 面试题库

面试题:C++中find算法在简单容器中的应用

假设有一个std::vector<int> vec,里面存储了一些整数。请使用C++ STL的find算法,在vec中查找特定整数(比如5),如果找到,输出其位置(索引值);如果没找到,输出提示信息。请写出完整的代码实现。
36.0万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

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

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5, 6};
    auto it = std::find(vec.begin(), vec.end(), 5);
    if (it != vec.end()) {
        std::cout << "找到数字5,其位置(索引值)为:" << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << "未找到数字5" << std::endl;
    }
    return 0;
}