C++与stack中使用pair的部分用法

创建带pair的stack

stack<pair<int,int>> s;

入栈操作

s.push({1,2});

出栈操作

s.pop();

读取栈顶的第一个,第二个元素

s.top().first;
s.top().second;

其他的基本功能,上个代码(从某英文网站上COPY的)

#include <bits/stdc++.h>
using namespace std;

// 打印栈顶内容
void printPair(pair<int, int> p)
{

    cout << "("
        << p.first << ", "
        << p.second << ") ";
}

// 打印栈的所有内容
void Showstack(stack<pair<int, int> > s)
{
    while (!s.empty()) {
        printPair(s.top());
        s.pop();
    }

    cout << '\n';
}

int main()
{
    stack<pair<int, int> > s;                //构造

    s.push({ 10, 20 });                            //入栈,注意是圆括号里面套花括号
    s.push({ 15, 5 });
    s.push({ 1, 5 });
    s.push({ 5, 10 });
    s.push({ 7, 9 });

    cout << "Stack of Pairs: ";
    Showstack(s);                                        //展示栈内容

    cout << "\nSize of Stack of Pairs: "
        << s.size();                                    //容量大小
    cout << "\nTop of Stack of Pairs: ";
    printPair(s.top());                            //输出栈顶数据

    cout << "\n\nRemoving the top pair\n";
    s.pop();                                                //弹出栈顶数据

    cout << "Current Stack of Pairs: ";
    Showstack(s);                                        //再次展示栈内容

    return 0;
}

本人水平有限目前就想到这么多,欢迎补充

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值