六月丁香五月婷婷,丁香五月婷婷网,欧美激情网站,日本护士xxxx,禁止18岁天天操夜夜操,18岁禁止1000免费,国产福利无码一区色费

學(xué)習(xí)啦 > 學(xué)習(xí)英語(yǔ) > 專業(yè)英語(yǔ) > 計(jì)算機(jī)英語(yǔ) > c中vector的用法

c中vector的用法

時(shí)間: 長(zhǎng)思709 分享

c中vector的用法

  c中vector的用法的用法你知道嗎?下面小編就跟你們?cè)敿?xì)介紹下c中vector的用法的用法,希望對(duì)你們有用。

  c中vector的用法的用法如下:

  1 基本操作

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

  (2)創(chuàng)建vector對(duì)象,vector<int> vec;

  (3)尾部插入數(shù)字:vec.push_back(a);

  (4)使用下標(biāo)訪問(wèn)元素,cout<<vec[0]<<endl;記住下標(biāo)是從0開(kāi)始的。

  (5)使用迭代器訪問(wèn)元素.

  vector<int>::iterator it;

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

  cout<<*it<<endl;

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

  (7)刪除元素: vec.erase(vec.begin()+2);刪除第3個(gè)元素

  vec.erase(vec.begin()+i,vec.end()+j);刪除區(qū)間[i,j-1];區(qū)間從0開(kāi)始

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

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

  2

  vector的元素不僅僅可以使int,double,string,還可以是結(jié)構(gòu)體,但是要注意:結(jié)構(gòu)體要定義為全局的,否則會(huì)出錯(cuò)。下面是一段簡(jiǎn)短的程序代碼:

  復(fù)制代碼

  #include<stdio.h>

  #include<algorithm>

  #include<vector>

  #include<iostream>

  using namespace std;

  typedef struct rect

  {

  int id;

  int length;

  int width;

  //對(duì)于向量元素是結(jié)構(gòu)體的,可在結(jié)構(gòu)體內(nèi)部定義比較函數(shù),下面按照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;

  }

  復(fù)制代碼

  3 算法

  (1) 使用reverse將元素翻轉(zhuǎn):需要頭文件#include<algorithm>

  reverse(vec.begin(),vec.end());將元素翻轉(zhuǎn)(在vector中,如果一個(gè)函數(shù)中需要兩個(gè)迭代器,

  一般后一個(gè)都不包含.)

  (2)使用sort排序:需要頭文件#include<algorithm>,

  sort(vec.begin(),vec.end());(默認(rèn)是按升序排列,即從小到大).

  可以通過(guò)重寫(xiě)排序比較函數(shù)按照降序比較,如下:

  定義排序比較函數(shù):

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

  {

  return a>b;

  }

  調(diào)用時(shí):sort(vec.begin(),vec.end(),Comp),這樣就降序排序。

熱門(mén)文章

543003