c++ std::pair

测试std::pair, 代码如下:

cpp 复制代码
#include <algorithm>

// pair返回多个数据。 还可以嵌套, 如pair<int, pair<int, string>>
pair<int, int> getMinAndMax(int a, int b) {
	int min = a < b ? a : b;
	int max = a > b ? a : b;
	return make_pair(min, max);
}

void testPair() {
	int a = 9527, b = 1605;
	pair<int, int> res = getMinAndMax(a, b);
	cout << "min: " << res.first << ", max: " << res.second << endl;

	// pair可以作为map的元素
	std::map<string, int> peopleKungFus;
	peopleKungFus.insert(std::pair<string, int>("段正淳", 75));  // 显式构造 pair
	peopleKungFus.insert(make_pair("田伯光", 85));           // 使用 make_pair
	peopleKungFus.emplace("南海神尼", 60);  // 直接构造
	for (const auto& pair : peopleKungFus) { // 按照key的排序顺序升序排列
		std::cout << "[" << pair.first << ", " << pair.second  << "] ";
	}
	cout << endl;

	// 将多个属性组合为 pair 后存入 vector 或 set,可实现多属性排序
	vector<pair<string, int>> kungFuScores = { {"挤奶龙抓手", 88}, {"葵花点穴手", 80}, {"一阳指", 99} };
	sort(kungFuScores.begin(), kungFuScores.end()); // 默认按 string(功夫名) 升序排序
	for (const auto& pair : kungFuScores) {
		std::cout << "[" << pair.first << ", " << pair.second << "] ";
	}
	cout << endl;
	sort(kungFuScores.begin(), kungFuScores.end(),
		[](const auto& a, const auto& b) {
			return a.second > b.second; // 按 int(功夫武力值) 降序排序
		});
	cout << "按照功夫武力值降序排列为:";
	for (const auto& pair : kungFuScores) {
		std::cout << "[" << pair.first << ", " << pair.second << "] ";
	}
	cout << endl;

	// 与 STL 算法协同工作, 这里是筛选数据,查找满足条件的第一个数.  使用find_if函数需包含头文件algorithm
	auto it = find_if(kungFuScores.begin(), kungFuScores.end(),
		[](const pair<string, int>& p) {
			return p.second > 80;
		});
	if (it != kungFuScores.end()) {
		cout << "武力值大于80的最高的武功是:" << it->first << ", 武力值为:" << it->second << endl;
	}
	else {
		cout << "未找到满足条件的数据" << endl;
	}
	
	cout << "武功武力值大于80的有:";
	it = kungFuScores.begin();
	for (;(it = find_if(it, kungFuScores.end(),[](const auto& p) { return p.second > 80; })) != kungFuScores.end();) {
		cout << it->first << ":" << it->second << " ";
		++it; // 跳过已处理项
	}
	cout << endl;
}

打印:

ok.

相关推荐
阿米亚波4 分钟前
【C++ STL】std::deque
数据结构·c++·笔记·算法·stl
yxlalm33 分钟前
2.java秒杀项目第二课-后端登录功能
java·开发语言
光学补偿41 分钟前
文件IO的前世今生
开发语言·学习·面试·java-ee
解局易否结局1 小时前
鸿蒙原生开发实战:用 Native C++ 与 OpenGL ES 构建高性能图形渲染管线
c++·elasticsearch·华为·harmonyos
Starmoon_dhw1 小时前
题解:P16108 「o.OI R-1」基础博弈练习题
c++·算法·图论
玖玥拾1 小时前
C# 语言进阶(十三)网络 DLL 库分层设计
服务器·开发语言·网络·网络协议·c#
2601_949816352 小时前
C++内存对齐与结构体填充深度精讲:底层规则、内存裁剪、适配优化与工程避坑
开发语言·arm开发·c++
浩瀚地学2 小时前
【面试算法笔记】0105-数组-螺旋矩阵
java·开发语言·笔记·算法·面试
Geek-Chow2 小时前
Mobile App Certificate Pinning: Underlying Principle and a Swift Example
开发语言·ios·swift·安全架构
王老师青少年编程2 小时前
2026年全国青少年信息素养大赛复赛真题(算法应用主题赛C++初中组:带解析)(7月11日试卷一)【文末附答案和解析】
c++·真题·答案·复赛·2026年·青少年信息素养大赛·算法应用主题赛