#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;
}
pair关键字
于 2025-01-26 11:49:23 首次发布