文章导航PC6首页软件下载单机游戏安卓资源苹果资源

pc软件新闻网络操作系统办公工具编程服务器软件评测

安卓新闻资讯应用教程刷机教程安卓游戏攻略tv资讯深度阅读综合安卓评测

苹果ios资讯苹果手机越狱备份教程美化教程ios软件教程mac教程

单机游戏角色扮演即时战略动作射击棋牌游戏体育竞技模拟经营其它游戏游戏工具

网游cf活动dnf活动lol周免英雄lol礼包

手游最新动态手游评测手游活动新游预告手游问答

您的位置:首页资讯编程开发 → c++ vector用法详解 c++ vector用法总结

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

时间:2017/8/18 15:59:24来源:www.pc6.com作者:0..0我要评论(0)

  c++ vector是在c++中开发过程中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),这样就降序排序。

相关视频

    没有数据

相关阅读 微信小程序有哪些功能好用 微信小程序排行榜TOP100faststone capture怎么截长图 faststone capture截长图教程最囧游戏我kao第十关怎么过 最囧游戏怎么帮助Tom猫喝到牛奶王者荣耀死亡率最高的英雄TOP10 王者荣耀最容易死的英雄是谁?最囧游戏2第6关攻略 最囧游戏2让tom高兴起来攻略vertus fluid mask教程 vertus fluid mask怎么用跳舞的线风暴怎么过 跳舞的线风暴The Storm视频通关攻略desktop.ini是什么文件 desktop.ini可以删除吗

文章评论
发表评论

热门文章 没有查询到任何记录。

最新文章 编程语言排行榜2020年android studio怎么删 eclipse怎么设置编码格式 eclipse设置编码格andriod studio如何使用真机测试 andriod sandroid studio怎么生成apk android studioandroid studio如何导入jar包 android stud

人气排行 安卓模拟器BlueStacks安装使用教程编程语言排行榜2020年9月 TIOBE编程语言排行eclipse字体大小怎么设置 eclipse字体大小plsql developer怎么连接数据库 plsql deveTomcat9.0安装教程 Tomcat9.0环境变量配置方plsql developer怎么使用 plsql developerVisual Studio 2015环境搭建教程Eclipse优化设置教程 Eclipse优化设置技巧