溫馨提示×

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

c++
小億
432
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女