在c++中:stack、queue、vector、nodelist

stack:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
using namespace std;
int main()
{
    stack<int>s;
    s.push(3);//放在栈顶
    s.push(7);
    s.push(1);
    cout<<s.size()<<" "<<endl;//输出长度
    cout<<s.top()<<endl;//输出栈顶元素
    s.pop();//删除栈顶元素
    cout<<s.top()<<endl;
    s.pop();
    cout<<s.top()<<endl;

    s.push(5);
    cout<<s.top()<<" "<<endl;
    s.pop();

    cout<<s.top()<<" "<<endl;
    return 0;  
}
/*
3
1
7
3
5
3
*/

queue:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
int main()
{
    queue<string>q;
    q.push("red");
    q.push("yellow");
    q.push("yellow");
    q.push("blue");
    cout<<q.front()<<" "<<endl;
    q.pop();
    cout<<q.front()<<" "<<endl;
    q.pop();
    cout<<q.front()<<" "<<endl;
    q.pop();
    q.push("green");
    cout<<q.front()<<" "<<endl;
    q.pop();
    cout<<q.front()<<" "<<endl;
}
/*
red
yellow
yellow
blue
green
*/

queue例子:

//pair是保存成对数值的结构体模板,make_pair用于生成一对数值,第一个元素通过first访问,第二个元素通过second访问。
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int n,q,t;
    string name;
    //使用标准库里的queue 
    queue<pair<string,int>>Q;
    scanf("%d%d",&n,&q);
    //使用标准库里的queue 
    for(int i = 0; i < n; i++)
    {
        scanf("%s %d",name,&t);
        Q.push(make_pair(name,t));
    }
    pair<string,int>u;
    int elaps = 0,a;
    //模拟
    while(!Q.empty())
    {
        u = Q.front();
        Q.pop();
        a = min(u.second,q);
        u.second -= a;
        elaps += a;
        if(u.second > 0 )
            Q.push(u);
        else
            cout<<u.first <<" "<<elaps<<endl; 
     } 
 } 

vector:

#include<iostream>
#include<vector>
using namespace std;
void print(vector<double>v)
{
    for(int i = 0; i < v.size(); i ++)
        cout<<v[i]<<" ";
    cout<<endl;
}
int main()
{
    vector<double>v;
    v.push_back(0.1);
    v.push_back(0.2);
    v.push_back(0.3);
    v[2] = 0.4;
    print(v);// 0.1 0.2 0.4
    v.insert(v.begin() + 2,0.8);//在v[2]处插入0.8 
    print(v);//0.1 0.2 0.8 0.4
    v.erase(v.begin() + 1);//删除v[1] 
    print(v);//0.1 0.8 0.4
    v.push_back(0.9);//在末尾加上x 
    print(v);//0.1 0.8 0.4 0.9
    v.clear();//删除v中所有元素
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qiulianshaonv_wjm/article/details/82464112