分别包含在文件<stack>,<queue>,<vector>
定义:
stack<class T> s;
queue<class T> q;
vector<class T> v;
stack的方法:
push() 的向容器顶部里插入元素;
pop() 是删除容器顶部的元素;
top() 返回容器顶部的元素;
size() 返回容器的元素个数;
empty() 是检查是否为空的方法
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack <int> n;
for ( int i = 1;i <= 5 ; i++ )
n.push(i) ; // 插入 当前栈为 5(顶)4 3 2 1
cout << "栈顶: " << n.top() << endl ;
n.pop(); // 删除容器顶部的元素
cout << "栈顶: " << n.top() <<endl ;
cout << "栈内元素有: " << n.size() << endl ;
if( !n.empty()) //判断是否栈空
cout << "栈非空!" <<endl ;
return 0;
}
queue的方法,它和stack很像:
back()返回队列最后一个元素引用
empty()是检查是否为空的方法
front()获得队列最前面一个元素引用
push()在队列尾添加一个数据
pop()删除队列头的一个数据
size()队列中元素个数
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue < int > n;
for ( int i = 1;i <= 5 ; i++ )
n.push(i) ; // 插入 当前队列为 1 2 3 4 5(尾)
cout << "队首为:"<< n.front() << endl ;
cout << "队尾为:"<< n.back() << endl;
n.pop(); // 删除队列首部的元素
cout << "队首为:"<< n.front() <<endl ; // 队首改变,变为2
cout << "队内元素为:" << n.size() << endl ;
if( !n.empty()) //判断队列是否为空
cout << "队列非空" <<endl ;
return 0;
}
vector的方法
vector容器是一个模板类,可以存放任何类型的对象(但必须是同一类对象)。
vector对象可以在运行时高效地添加元素,并且vector中元素是连续存储的。
vector的构造函数:
vector<string> v1; // 创建空容器,其对象类型为string类
vector<string> v2(10); // 创建有10个具有初始值(即空串)的string类对象的容器
vector<string> v3(5, "hello"); // 创建有5个值为“hello”的string类对象的容器
vector<string> v4(v3.begin(), v3.end()); // v4是与v3相同的容器(完全复制)
void push_back(x); // 向容器末尾添加一个元素
void pop_back(); // 弹出容器中最后一个元素(容器必须非空)
vector<int>::iterator iter=v.begin();//初始化迭代器,让他指向v的开始。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector <int> n;
for ( int i = 1;i <= 5 ; i++ )
n.push_back(i) ; // 插入 当容器为 5(尾)4 3 2 1
cout << "容器顶部: " << n.front() << endl ;
n.pop_back(); // 删除容器顶部的元素
cout << "容器顶部: " << n.front() <<endl ;
cout << "容器内元素有: " << n.size() << endl ;
n.erase( n.begin()); // 删除一个元素
cout << "容器顶部: " << n.front() <<endl ;
if( !n.empty() ) //判断是否栈空
cout << "容器非空!" <<endl ;
n.clear(); //清空容器
if( n.empty() )
cout << "容器为空!" <<endl ;
return 0;
} //最后这个没有用两个向量容器的函数,明天要回家,要收拾东西了,嘿嘿
vector对象可以在运行时高效地添加元素,并且vector中元素是连续存储的。
vector的构造函数:
vector<string> v1; // 创建空容器,其对象类型为string类
vector<string> v2(10); // 创建有10个具有初始值(即空串)的string类对象的容器
vector<string> v3(5, "hello"); // 创建有5个值为“hello”的string类对象的容器
vector<string> v4(v3.begin(), v3.end()); // v4是与v3相同的容器(完全复制)
void push_back(x); // 向容器末尾添加一个元素
void pop_back(); // 弹出容器中最后一个元素(容器必须非空)
vector<int>::iterator iter=v.begin();//初始化迭代器,让他指向v的开始。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector <int> n;
for ( int i = 1;i <= 5 ; i++ )
n.push_back(i) ; // 插入 当容器为 5(尾)4 3 2 1
cout << "容器顶部: " << n.front() << endl ;
n.pop_back(); // 删除容器顶部的元素
cout << "容器顶部: " << n.front() <<endl ;
cout << "容器内元素有: " << n.size() << endl ;
n.erase( n.begin()); // 删除一个元素
cout << "容器顶部: " << n.front() <<endl ;
if( !n.empty() ) //判断是否栈空
cout << "容器非空!" <<endl ;
n.clear(); //清空容器
if( n.empty() )
cout << "容器为空!" <<endl ;
return 0;
} //最后这个没有用两个向量容器的函数,明天要回家,要收拾东西了,嘿嘿