数据结构:字符串、栈、队列、数组、链表、二叉树
c++中STL常用的数据结构:
string、stack、queue、deque、vector、list、map、iterators
push(): 向栈内压入一个成员;
pop(): 从栈顶弹出一个成员;
empty(): 如果栈为空返回true,否则返回false;
top(): 返回栈顶,但不删除成员;
size(): 返回栈内元素的大小;
#include
#include
using namespace std;
int main()
{
stack <int>stk;
for(int i=0;i<10;i++) //入栈
stk.push(i);
cout<<"栈的大小:"<while(!stk.empty()){
cout<cout<<"栈的大小:"<
运行结果:
栈的大小:10
9
8
7
6
5
4
3
2
1
0
栈的大小:0
#include
#include
using namespace std;
#define MAXSIZE 0xffff
template<class type>
class my_stack
{
int top;
type* my_s;
int maxsize;
public:
my_stack():top(-1),maxsize(MAXSIZE)
{
my_s=new type[maxsize];
if(my_s==NULL)
{
cerr<<"动态存储分配失败!"<1);
}
}
my_stack(int size):top(-1),maxsize(size)
{
my_s=new type[maxsize];
if(my_s==NULL)
{
cerr<<"动态存储分配失败!"<1);
}
}
~my_stack()
{
delete[] my_s;
}
//是否为空
bool Empty();
//压栈
void Push(type tp);
//返回栈顶元素
type Top();
//出栈
void Pop();
//栈大小
int Size();
};
template<class type>
bool my_stack<type>::Empty()
{
if(top==-1)
return true;
else
return false;
}
template<class type>
type my_stack<type>::Top()
{
if(top!=-1)
return my_s[top];
else{
cout<<"栈空\n";
exit(1);
}
}
template<class type>
void my_stack<type>::Push(type tp)
{
if(top+1else{
cout<<"栈满\n";
exit(1);
}
}
template<class type>
void my_stack<type>::Pop()
{
if(top>=0)
top--;
else {
cout<<"栈空\n";
exit(1);
}
}
template<class type>
int my_stack<type>::Size()
{
return top+1;
}
然后就可以在另一个cpp文件中使用它(记得include):
#include
#include "my_stack.cpp"
using namespace std;
int main()
{
my_stack<int> stk;
for(int i=0;i<50;i++)
stk.Push(i);
cout<<"栈的大小:"<while(!stk.Empty()){
cout<cout<<"栈的大小:"<<sizeof(stk)<
q.empty() 如果队列为空返回true,否则返回false
q.size() 返回队列中元素的个数
q.pop() 删除队列首元素但不返回其值
q.push() 在队尾压入新元素
q.front() 返回队首元素的值,但不删除该元素
q.back() 返回队列尾元素的值,但不删除该元素
#include
#include
using namespace std;
int main()
{
queue <int> q;
for(int i=0;i<10;i++) //入栈
q.push(i);
cout<<"栈的大小:"<cout<<"返回队首元素,但不删除:"<cout<<"返回队尾元素,但不删除:"<while(!q.empty()){
cout<cout<<"栈的大小:"<
栈的大小:10
返回队首元素,但不删除:9
返回队尾元素,但不删除:0
0
1
2
3
4
5
6
7
8
9
栈的大小:0
deque k; 定义一个deque的变量(定义时已经初始化)
例如: deque<int> k;
k.empty() ------ 查看是否为空范例,是的话返回1,不是返回0
k.clear() ------ 清除队列里的所有数据
k.push_front(i)------ 从已有元素前面增加元素i(队伍大小不预设)
k.push_back(i) ------ 从已有元素后面增加元素i(队伍大小不预设)
k.pop_front() ------ 清除第一个元素
k.pop_back() ------ 清除最后一个元素
k.front() ------ 显示第一个元素
k.back() ------ 显示最后一个元素
k.size() ------ 输出现有元素的个数
#include
#include
using namespace std;
int main()
{
int i;
int a[10] = {0,1,2,3,4,5,6,7,8,9};
deque<int> q;
for(i=0;i<=9;i++){
if(i%2==0)
q.push_front(a[i]);
else
q.push_back(a[i]);
}
/*此时队列里的内容是: {8,6,4,2,0,1,3,5,7,9}*/
q.pop_front();
cout</*清除第一个元素后输出第一个(6)*/
q.pop_back();
cout</*清除最后一个元素后输出最后一个(7)*/
}
运行结果:
6
7