c++里面一些容器问题

来源:互联网 发布:平板双系统安装软件 编辑:程序博客网 时间:2024/05/11 21:09

stack用法:

stack <int> std;

std.push(...);

int a=std.top();

std.pop();

栈类:

#define max=100;

class  stack

{

int top;

int arry[max];

public:

stack()

{

top=-1;

}

...

}

队列queue:

queue <int> que;
que.push(1);
que.push(2);
que.pop();
cout<<que.front();

双端队列deque:可以实现对队列尾的操控。

que.push_front()  

que.pop_front()

que.back()//队尾元素

不如直接用数组当队列使。。。

int que[100,front=0,rear=0;...

vector用法:iterator是迭代器,vector像是动态数组

vector <int> a;
a.push_back(1);
a.push_back(2);
for(vector<int>::iterator it=a.begin();it!=a.end();++it)
cout<<*it;

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

删除元素:    vec.erase(vec.begin()+2);删除第3个元素

vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始

向量大小:vec.size();

清空:vec.clear();

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


0 0
原创粉丝点击