温馨提示×

c++中vector怎么查找指定元素

c++
小亿
109
2024-02-27 11:49:55
栏目: 编程语言

在C++中,可以使用std::find算法来查找指定元素在vector中的位置。下面是一个示例代码:

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

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

    int target = 3;

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

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

    return 0;
}

在上面的代码中,我们定义了一个vector vec,然后使用std::find算法来查找元素3在vector中的位置。如果找到了该元素,将输出其索引;如果没有找到,将输出提示信息。

0