c++vector用法详解c++vector用法总结

c++ vector是在c++中开发过程中c++ vector作为一个十分有用的容器,许多朋友还不是很清楚c++ vector用法,不知道c++ vector到底有什么优秀的用法,不用着急一起来看看c++ vector用法详解来增加自身对c++ vector的了解吧。

c++vector用法详解c++vector用法总结_商务服务_庆典活动

1:基本操作


(1)头文件#include<vector>.


(2)创建vector对象,vector<int> vec;


(3)尾部插入数字:vec.push_back(a);


(4)使用下标访问元素,cout<<vec[0]<<endl;记住下标是从0开始的。


(5)使用迭代器访问元素.

vector<int>::iterator it;

for(it=vec.begin();it!=vec.end();it++)

cout<<*it<<endl;


(6)插入元素:    vec.insert(vec.begin()+i,a);在第i+1个元素前面插入a;


(7)删除元素:    vec.erase(vec.begin()+2);删除第3个元素

vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始


(8)向量大小:vec.size();


(9)清空:vec.clear();


2:vector的元素不仅仅可以使int,double,string,还可以是结构体,但是要注意:结构体要定义为全局的,否则会出错。


  #include<stdio.h>

  #include<algorithm>

  #include<vector>

  #include<iostream>

  using namespace std;

  typedef struct rect

  {

  int id;

  int length;

  int width;

  //对于向量元素是结构体的,可在结构体内部定义比较函数,下面按照id,length,width升序排序。


  bool operator< (const rect &a)  const

  {

  if(id!=a.id)

  return id<a.id;

  else

  {

  if(length!=a.length)

  return length<a.length;

  else

  return width<a.width;

  }

  }

  }Rect;


  int main()

  {

  vector<Rect> vec;

  Rect rect;

  rect.id=1;

  rect.length=2;

  rect.width=3;

  vec.push_back(rect);

  vector<Rect>::iterator it=vec.begin();

  cout<<(*it).id<<<<(*it).length<<<<(*it).width<<endl;

  return 0;

  }


3:算法


(1) 使用reverse将元素翻转:需要头文件#include<algorithm>


reverse(vec.begin(),vec.end());将元素翻转(在vector中,如果一个函数中需要两个迭代器,


一般后一个都不包含.)


(2)使用sort排序:需要头文件#include<algorithm>,sort(vec.begin(),vec.end());(默认是按升序排列,即从小到大).


可以通过重写排序比较函数按照降序比较,如下:


定义排序比较函数:


bool Comp(const int &a,const int &b)

  {

  return a>b;

  }


调用时:sort(vec.begin(),vec.end(),Comp),这样就降序排序。


61
18
0
65

相关资讯

  1. 1、小米4G时代的最后旗舰!小米商城大幅促销2491
  2. 2、四块通过软RAID组合在一起:别致的8TBSSD811
  3. 3、华为P40Pro红旗版泄露徕卡拍照大变402
  4. 4、LG英特尔结盟打造无线显示传输技术4842
  5. 5、本周四《鬼泣》前三部合集将上架Switch4633
  6. 6、LGD让步南京工厂罢工事件平息2732
  7. 7、三星GalaxyM40会在6月11日现身?5079
  8. 8、开源磁盘分区工具Gparted1.1.0来了:轻松读取FAT16/FAT32格式3757
  9. 9、专注语音交互!苹果可能推SiriOS1830
  10. 10、雅虎圣诞期间裁员600人员工泄露补偿规定将失补偿机会2690
全部评论(0)
我也有话说
0
收藏
点赞
顶部