溫馨提示×

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

c++
小億
263
2024-03-07 13:08:23
欄目: 編程語言

要使用vector查找指定元素,可以使用std::find函數。具體操作如下:

#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,并且查找其中是否存在值為3的元素。使用std::find函數可以在vector中查找指定元素,并返回該元素的迭代器。如果找到了元素,則輸出元素所在的索引位置,如果未找到則輸出"Element not found"。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女