vector怎么查找特定元素位置

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

要查找特定元素在一个vector中的位置,您可以使用std::find函数来实现。下面是一个示例代码:

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

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

    int element = 3; // 要查找的元素

    auto it = std::find(vec.begin(), vec.end(), element);
    
    if (it != vec.end()) {
        std::cout << "Element found at position: " << std::distance(vec.begin(), it) << std::endl;
    } else {
        std::cout << "Element not found in the vector" << std::endl;
    }

    return 0;
}

在上面的示例中,我们首先定义一个整数类型的vector,并且定义要查找的元素为3。然后使用std::find函数在vector中查找这个元素,如果找到了就输出该元素在vector中的位置,否则输出未找到的提示。

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

推荐阅读: vector的push_back函数怎么使用