温馨提示×

vector怎么查找指定元素

小亿
309
2024-01-22 09:11:58
栏目: 编程语言

要在vector中查找指定元素,可以使用std::find函数。以下是示例代码:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // 查找元素3
    int target = 3;
    auto it = std::find(vec.begin(), vec.end(), target);

    if (it != vec.end()) {
        std::cout << "找到了元素" << target << std::endl;
    } else {
        std::cout << "未找到元素" << target << std::endl;
    }

    return 0;
}

上述代码中,使用std::find函数在vector中查找元素3。如果找到了该元素,则输出"找到了元素3";如果未找到,则输出"未找到元素3"。

0