vector怎么查找指定元素

1657
2024/1/21 9:11:58
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在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"。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: vector容器如何删除指定元素