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的长度是可变的,而数组的下标是不变的。