高性价比
国外便宜VPS服务器推荐

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

在C++中,vector是一种常用的容器类型,它可以动态地存储和访问元素。当我们需要在vector中查找某个特定的值时,可以使用STL提供的find()算法,也可以使用vector自带的成员函数find()。本文将从多个方面详细阐述如何使用vector查找某个值。

一、使用STL的find()算法查找

STL(Standard Template Library)是C++标准库的一部分,提供了一系列基本数据结构和算法,其中包括了查找算法。STL的find()算法可以用于查找一个特定的值在vector中的位置,其函数原型如下:

template

InputIterator find (InputIterator first, InputIterator last, const T& val);

其中,first和last分别是vector的起始和结束迭代器,val是要查找的值。find()算法返回一个迭代器,指向vector中第一个匹配val的元素。如果vector中不存在val,则返回last迭代器。

下面是一个使用STL的find()算法查找vector中某个值的示例代码:

#include

#include

#include

int main() {

std::vector vec = {1, 2, 3, 4, 5};

int val = 3;

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

if (it != vec.end()) {

std::cout << "Found " << val << " at position " << it – vec.begin() << std::endl;

} else {

std::cout << val << " not found" << std::endl;

}

return 0;

运行结果如下:

Found 3 at position 2

二、使用vector的find()成员函数查找

除了使用STL提供的find()算法,我们还可以直接使用vector自带的find()成员函数来查找某个值。vector的find()函数的函数原型如下:

iterator find (const value_type& val);

其中,val是要查找的值,函数返回一个迭代器,指向vector中第一个匹配val的元素。如果vector中不存在val,则返回end()迭代器。

下面是一个使用vector的find()成员函数查找某个值的示例代码:

#include

#include

int main() {

std::vector vec = {1, 2, 3, 4, 5};

int val = 3;

auto it = vec.find(val);

if (it != vec.end()) {

std::cout << "Found " << val << " at position " << it – vec.begin() << std::endl;

} else {

std::cout << val << " not found" << std::endl;

}

return 0;

运行结果与前面的示例代码相同。

三、使用自定义比较函数查找

在某些情况下,我们需要使用自定义的比较函数来查找vector中的元素。例如,我们需要查找一个字符串vector中长度最长的字符串,可以使用自定义的比较函数来实现。下面是一个使用自定义比较函数查找vector中最长字符串的示例代码:

#include

#include

#include

bool cmp(const std::string& s1, const std::string& s2) {

return s1.length() > s2.length();

int main() {

std::vector vec = {“hello”, “world”, “cpp”, “programming”};

auto it = std::max_element(vec.begin(), vec.end(), cmp);

std::cout << "Longest string is " << *it << std::endl;

return 0;

运行结果如下:

Longest string is programming

四、使用二分查找算法查找有序vector

如果我们需要在有序的vector中查找某个值,可以使用二分查找算法来提高查找效率。C++标准库提供了二分查找算法std::binary_search()和std::lower_bound(),分别用于判断某个值是否存在和查找第一个大于等于该值的位置。下面是一个使用std::binary_search()和std::lower_bound()查找有序vector中某个值的示例代码:

#include

#include

#include

int main() {

std::vector vec = {1, 3, 5, 7, 9};

int val = 5;

bool found = std::binary_search(vec.begin(), vec.end(), val);

if (found) {

std::cout << val << " found" << std::endl;

} else {

std::cout << val << " not found" << std::endl;

}

auto it = std::lower_bound(vec.begin(), vec.end(), val);

std::cout <= ” << val << " is " << *it << std::endl;

return 0;

运行结果如下:

5 found

First element >= 5 is 5

本文从使用STL的find()算法、使用vector的find()成员函数、使用自定义比较函数查找、使用二分查找算法查找有序vector等多个方面详细阐述了如何在C++中使用vector查找某个值。在实际编程中,我们可以根据具体的需求选择不同的查找方法,以提高程序的效率和可读性。

未经允许不得转载:一万网络 » c++中怎样用vector查找某个值