c中vector的用法的用法你知道吗?下面小编就跟你们详细介绍下c中vector的用法的用法,希望对你们有用。
c中vector的用法的用法如下:
1 基本操作
(1)头文件#include<vector>.
(2)创建vector对象,vector<int> vec;
(3)尾部插入数字:_back(a);
(4)使用下标访问元素,cout<<vec[0]<<endl;记住下标是从0开始的。
(5)使用迭代器访问元素.
vector<int>::iterator it;
for(it=n();it!=();it++)
cout<<*it<<endl;
(6)插入元素: rt(n()+i,a);在第i+1个元素前面插入a;
(7)删除元素: e(n()+2);删除第3个元素
e(n()+i,()+j);删除区间[i,j-1];区间从0开始
(8)向量大小:();
(9)清空:r();
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!=)
return id<;
else
{
if(length!=th)
return length<th;
else
return width<h;
}
}
}Rect;
int main()
{
vector<Rect> vec;
Rect rect;
=1;
th=2;
h=3;
_back(rect);
vector<Rect>::iterator it=n();
cout<<(*it)<<' '<<(*it)th<<' '<<(*it)h<<endl;
return 0;
}
复制代码
3 算法
(1) 使用reverse将元素翻转:需要头文件#include<algorithm>
reverse(n(),());将元素翻转(在vector中,如果一个函数中需要两个迭代器,
一般后一个都不包含.)
(2)使用sort排序:需要头文件#include<algorithm>,
sort(n(),());(默认是按升序排列,即从小到大).
可以通过重写排序比较函数按照降序比较,如下:
定义排序比较函数:
bool Comp(const int &a,const int &b)
{
return a>b;
}
调用时:sort(n(),(),Comp),这样就降序排序。