第一、栈(stack)(后进先出)
使用栈,要先包括头文件#include<stack>
定义栈,一下形式实现
stack<Type>s;其中Type为数据类型(如int ,char,float等)
栈的主要操作:
s.push(item);//将item压入栈顶
s.pop();//删除栈顶的元素,但是不会返回
s.top();//返回栈顶的元素,但是不会删除
s.size();//返回栈中元素的个数
s.empty();//检查栈是否为空,如果为空返回ture,否则返回false;
栈操作举例CODE:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int main()
{
stack <int> s;
int num;
cout<<"------Test for Stack-----"<<endl;
cout<<"Input number:"<<endl;
while(cin>>num)
{
s.push(num);
}
cout<<"The Stack has "<<s.size()<<" number.they are:"<<endl;
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
cout<<"\nNow the size is "<<s.size()<<endl;
//system("Pause");
}
第二、队列(queue)(先进先出)
使用队列,要先包含头文件:#include<queue>
定义队列,以如下形式实现:queue<Type>q;其中Type为数据类型(如Int,float,char等)
队列的主要操作:
q.push(item)//将item压入队列尾部
q.pop();//删除队尾首元素,但不返回
q.front();//返回队尾元素,但不删除
q.back();//返回队尾元素,但不删除
q.size();//返回队列中元素的个数
q.empty();//检查队列是否为空,如果为空返回ture,否则返回false
队列操作举CODE:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int main()
{
queue<int>q;
int num;
cout<<"------Test for Queue-----"<<endl;
cout<<"Input number:"<<endl;
while(cin>>num)
{
q.push(num);
}
cout<<"Now the Queue has "<<q.size()<<" number."<<endl;
cout<<"The first is "<<q.front()<<endl;
cout<<"The last is "<<q.back()<<endl;
cout<<"All numbers: "<<endl;
while(!q.empty())
{
cout<<q.front()<<" ";
q.pop();
}
cout<<"\nNow the Queue is "<<q.size()<<" number."<<endl;
//system("Pause");
}
第三、指针
1、定义指针对象
定义指针变量时,在变量名前写一个 * 星号,这个变量就变成了对应变量类型的指针变量。必要时要加( ) 来避免优先级的问题:
int* p_int; //指向int类型变量的指针
double* p_double; //指向double类型变量的指针
Student* p_struct; //类或结构体类型的指针
int** p_pointer; //指向 一个整形变量指针的指针
int(*p_arr)[3]; //指向含有3个int元素的数组的指针
int(*p_func)(int,int); //指向返回类型为int,有2个int形参的函数的指针
2、获取对象地址
指针用于存放某个对象的地址,要想获取该地址,虚使用取地址符(&),如下:
int add(int a , int b)
{
return a + b;
}
int main(void)
{
int num = 97;
float score = 10.00F;
int arr[3] = {1,2,3};
int* p_num = #
int* p_arr1 = arr; //p_arr1意思是指向数组第一个元素的指针
float* p_score = &score;
int (*p_arr)[3] = &arr;
int (*fp_add)(int ,int ) = add; //p_add是指向函数add的函数指针
const char* p_msg = "Hello world";//p_msg是指向字符数组的指针
return 0;
}
3、函数的指针
每一个函数本身也是一种程序数据,一个函数包含了多条执行语句,它被编译后,实质上是多条机器指令的合集。在程序载入到内存后,函数的机器指令存放在一个特定的逻辑区域:代码区。既然是存放在内存中,那么函数也是有自己的指针的。
int add(int a,int b) //函数的定义
{
return a + b;
}
int (*function)(int,int); //函数指针的声明
function = add; //给函数指针赋值
function = &add; //跟上面是一样的
int c = function(1,2); //跟函数名一样使用
int d = (*function)(1,2); //跟上面的调用是一样的
4、常量指针
int a = 97;
int b = 98;
int* const p = &a;
*p = 98; //正确
p = &b; //编译出错
第四、引用
#include<iostream>
using namespace std;
int main(int argc,char** argv)
{
int i=10;
int& ref=i;
ref++;
cout<<"i="<<i<<endl;
cout<<"ref="<<ref<<endl;
int j=20;
ref=j;
ref++;
cout<<"i="<<i<<endl;
cout<<"ref="<<ref<<endl;
cout<<"j="<<j<<endl;
return 0;
}
对ref的++操作是直接反应到所指变量之上,对引用变量ref重新赋值”ref=j”,并不会改变ref的指向,它仍然指向的是i,而不是j。理所当然,这时对ref进行++操作不会影响到j。而这些换做是指针的话,情况大不相同,请自行实验。输出结果如下:
i=11
ref=11
i=21
ref=21
j=20
完!