c++中怎么用vector查找某个值

2718
2024/3/19 17:31:38
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用std::find函数在vector中查找某个特定值。下面是一个示例代码:

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

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

    int value_to_find = 3;

    auto it = std::find(vec.begin(), vec.end(), value_to_find);

    if (it != vec.end()) {
        std::cout << "Value found at index " << it - vec.begin() << std::endl;
    } else {
        std::cout << "Value not found" << std::endl;
    }

    return 0;
}

在这个示例中,我们首先创建一个包含整数的vector,并定义要查找的值为3。然后使用std::find函数在vector中查找这个值,如果找到则输出其索引,否则输出"value not found"。

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

推荐阅读: 如何在C++项目中使用Clang编译器