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.

相关推荐
苦夏木禾25 分钟前
js请求避免缓存的三种方式
开发语言·javascript·缓存
超级土豆粉34 分钟前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
wei_shuo2 小时前
飞算 JavaAI 开发助手:深度学习驱动下的 Java 全链路智能开发新范式
java·开发语言·飞算javaai
熊猫钓鱼>_>2 小时前
用Python解锁图像处理之力:从基础到智能应用的深度探索
开发语言·图像处理·python
小小小小王王王2 小时前
求猪肉价格最大值
数据结构·c++·算法
GO兔2 小时前
开篇:GORM入门——Go语言的ORM王者
开发语言·后端·golang·go
好开心啊没烦恼2 小时前
Python 数据分析:numpy,抽提,整数数组索引与基本索引扩展(元组传参)。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy·pandas
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
future14123 小时前
C#学习日记
开发语言·学习·c#
码农编程录3 小时前
【c/c++3】类和对象,vector容器,类继承和多态,systemd,std&boost
c++