您的位置:首页 > 编程语言 > C语言/C++

c++中vector的使用方法

2017-12-19 17:17 323 查看
在c++中,vector的作用是:它能够像容器一样存放各种类型的对象,简单地说,vector是一个能够存放任意类型的动态数组,能够增加和压缩数据。

1 、基本操作

#include<iostream>
#include<vector>        //头文件
#include<string>
#include<algorithm>
using namespace std;
int main()
{

vector<int> vec;        //创建vector对象
//vector<vector<Point2f> > points; //定义一个二维数组
//points[0].size();  //指第一行的列数

vec.push_back(1);
vec.push_back(1);
vec.push_back(3);
vec.push_back(4);
vec.push_back(1);        //尾部插入数字
//vec.insert(vec.begin()+i,a);//在第i+1个元素前面插入a;
cout<<vec[0]<<endl;         //记住下标是从0开始的

vector<int>::iterator itr = vec.begin();//使用迭代器访问元素

while ( itr != vec.end())
{
if (1 == *itr)
{
itr = vec.erase(itr);            //删除元素
//vec.erase(vec.begin()+2);//删除第3个元素
//vec.erase(vec.begin()+i,vec.end()+j);//删除区间[i,j-1];区间从0开始
}
else
++itr;
}

for (itr =vec.begin(); itr != vec.end(); itr++)//使用begin和end来循环
{
cout << *itr << endl;
itr++;
}

vec.size();                 //向量大小
vec.clear();                //清空

return 0;
}


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),这样就降序排序。

输出Vector的中的元素

vector”float” vecClass;

int nSize = vecClass.size();

https://www.cnblogs.com/90zeng/p/Vector_erase.html

http://blog.csdn.net/duan19920101/article/details/50617190
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ vector