vector的find及迭代器使用

简介: (1)vector中find的使用vector本身没有find方法,是利用了头文件algorithm

(1)vector中find的使用

vector本身没有find方法,是利用了头文件algorithm

#include<iostream>
#include<algorithm>//注意要加这个
#include<vector>
int main(){
  using namespace std;
  vector<int> vec;
  vec.push_back(1);
  vec.push_back(2);
  vec.push_back(3);
  vec.push_back(4);
  vec.push_back(5);
  vec.push_back(6);
  vector<int>::iterator it=find(vec.begin(),vec.end(),4);
  if(it != vec.end())
    cout<<*it<<endl;
  else
    cout<<"can not find"<<endl;
  system("pause");
  return 0;
}

注意:vector<int>::iterator it=find..这句也可以写成auto it=find...,即由于上面已经定义了vector类型的vec,下面的it可以直接auto自动确定类型。

结果运行如下

image.png

(2)vector使用迭代器

  vector<int>c(20,2);//定义时指定vector的大小并把所有的元素赋一个特定的值
  for(int i=0;i<c.size();i++){
    cout<<c[i]<<" ";
  }//输出方法一
  cout<<endl;
  for(auto it=c.begin();it!=c.end();it++){
    cout<<*it<<" ";
  }//输出方法二
相关文章
|
11月前
|
存储 Cloud Native Linux
C++ 什么时候使用 vector、list、以及 deque?
C++ 什么时候使用 vector、list、以及 deque?
|
4月前
|
编译器 C语言 C++
C++ STL中list迭代器的实现
C++ STL中list迭代器的实现
C++ STL中list迭代器的实现
|
4月前
|
C++ 容器
【c++】优先级队列|反向迭代器(vector|list)
【c++】优先级队列|反向迭代器(vector|list)
33 0
|
5月前
list转迭代器Iterator
list转迭代器Iterator
|
5月前
std::vector不隐式拷贝进行添加元素
std::vector不隐式拷贝进行添加元素
|
算法 C++ 容器
C++ std::remove/std::remove_if/erase用法探讨
std::remove 不会改变输入vector/string的长度。其过程相当于去除指定的字符,剩余字符往前靠。后面的和原始字符保持一致。
131 0
【C++STL】list的反向迭代器
【C++STL】list的反向迭代器
64 0
|
算法 容器
使用迭代器输出vector里面的元素
使用迭代器输出vector里面的元素
86 0
|
安全 容器
别被vector最后一个元素erase错误
别被vector最后一个元素erase错误
165 0
别被vector最后一个元素erase错误