C++中vector的使用方法

xiaoxiao2021-02-27  328

  在C++中,vector是一个非常有用的容器,下面对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);删除第三个元素。           vec.erase(vec.begin()+i,vec.end()+j);删除第i+1个元素。 (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; 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、关于vector的算法 (1)使用reverse将元素翻转,头文件#include<algorithm>,函数reverse(vec.begin(),vec.end())。 (2)使用sort排序,头文件#include<algorithm>,函数sort(vec.begin(),vec.end())。排序函数默认是升序。 (3)降序算法:首先定义排序比较函数 bool Comp(const int &a,const int &b) { return a>b; } 调用时:sort(vec.begin(),vec.end(),Comp);这样就降序排序 4、vector比较 (1)vector和quene的比较:相同点:vector和queue都可以直接获得首尾的值(vector.begin()、vector.end()、queue.front()、queue.back())。不同点:vector只能push,而queue既可以push也可以pop。 (2)vector和数组的比较:相同点:vector和数组都可以通过下标访问。不同点:vector的长度是可变的,而数组的下标是不变的。

转载请注明原文地址: https://www.6miu.com/read-2004.html

最新回复(0)