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.

相关推荐
Edingbrugh.南空20 分钟前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
CodeCraft Studio1 小时前
借助Aspose.HTML控件,在 Python 中将 HTML 转换为 Markdown
开发语言·python·html·markdown·aspose·html转markdown·asposel.html
QQ_4376643141 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
aramae1 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
封奚泽优1 小时前
使用Python实现单词记忆软件
开发语言·python·random·qpushbutton·qtwidgets·qtcore·qtgui
liulilittle2 小时前
C++/CLI与标准C++的语法差异(一)
开发语言·c++·.net·cli·clr·托管·原生
daixin88482 小时前
什么是缓存雪崩?缓存击穿?缓存穿透?分别如何解决?什么是缓存预热?
java·开发语言·redis·缓存
小狄同学呀2 小时前
VS插件报错,g++却完美编译?API调用错因分析
c++
程序员编程指南3 小时前
Qt 数据库连接池实现与管理
c语言·数据库·c++·qt·oracle
你我约定有三3 小时前
RabbitMQ--消息丢失问题及解决
java·开发语言·分布式·后端·rabbitmq·ruby