要使用vector查找指定元素,可以使用std::find函数。具体操作如下:
要使用vector查找指定元素,可以使用std::find函数。具体操作如下:
#include<iostream>
#include<vector>
#include<algorithm>
intmain(){
std::vector<int>vec={1,2,3,4,5};
inttarget=3;
autoit=std::find(vec.begin(),vec.end(),target);
if(it!=vec.end()){
std::cout<<"Elementfoundatindex:"<<std::distance(vec.begin(),it)<<std::endl;
}else{
std::cout<<"Elementnotfound"<<std::endl;
}
return0;
}
在上面的代码中,我们定义了一个vector,并且查找其中是否存在值为3的元素。使用std::find函数可以在vector中查找指定元素,并返回该元素的迭代器。如果找到了元素,则输出元素所在的索引位置,如果未找到则输出"Elementnotfound"。
版权声明
本文仅代表作者观点,不代表博信信息网立场。