pair关键字

#include <iostream>
#include <utility>
#include <vector>
#include <string>

// 定义 Person 结构体
struct Person {
    std::string name;
    int age;
};

int main() {
    // 定义并初始化 std::pair 对象 p
    std::pair<int, std::string> p(1, "小明");
    std::cout << "学号" << p.first << "\n姓名" << p.second << std::endl;

    // 定义并默认初始化 std::pair 对象 a
    std::pair<int, float> a;
    std::cout << a.first << '\n' << a.second << '\n';

    // 定义并默认初始化 std::pair 对象 b
    std::pair<long long, std::string> b;
    std::cout << b.first << '\n' << b.second << std::endl;

    // make_pair()
    std::pair<std::string, int> person = std::make_pair("student", 90);
    std::cout << person.first << person.second << std::endl;

    // 创建一个 people 向量
    std::vector<Person> people;
    // 正确添加元素到 people 对象 
    people.push_back({"同学A", 18});
    people.push_back({"同学B", 19});
    people.push_back({"同学C", 20});

    // 创建一个 pair 向量,每个 pair 包含一个 Person 对象和一个分数
    std::vector<std::pair<Person, int>> scores;
    // 正确添加元素到 scores 向量
    scores.push_back({people[0], 90});
    scores.push_back({people[1], 80});
    scores.push_back({people[2], 70});

    // 遍历 scores 向量并输出信息
    for (const auto& item : scores) {
        std::cout << "name:" << item.first.name << '\n';
        std::cout << "age:" << item.first.age << '\n';
        std::cout << "score:" << item.second << std::endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值