C++系列-STL容器中的pair对组

STL容器中的pair对组

pair是一种将两个不同类型的值组合成一对的数据结构。如果想返回两个返回值,可以用对组。

对组的创建方式

  • pair<type1, type2> p (value1, value2)
  • pair<type1, type2> p = make_pair(value1, value2)

访问成员

  • 使用成员属性first, second分别访问pair中的两个值。
cpp 复制代码
code:
#include <iostream>
#include <set>
using namespace std;

void test01()
{
	// pair<type1, type2> p (value1, value2)
	pair<string, int> p1("张三", 88);
	cout << "p1.first: " << p1.first << ", p1.second: " << p1.second << endl;

	// pair<type1, type2> p = make_pair(value1, value2)
	pair<string, int> p2 = make_pair("李四", 66);
	cout << "p2.first: " << p2.first << ", p2.second: " << p2.second << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

result:
p1.first: 张三, p1.second: 88
p2.first: 李四, p2.second: 66

使用场景

作为函数的返回值

  • 函数返回pair对象,同时有两个类型的值。

存储键值对

-当存储两个相关值的时候用pair很方便。

容器操作

在一些关联容器中,如map set中,返回值或者是存储的元素就是pair类型,表示的要么是键值对,要么是同时返回的两个值。

cpp 复制代码
code:
#include <iostream>
#include <set>
#include <map>
using namespace std;

class Student
{
public:
	Student(string name, int age)
	{
		m_name = name;
		m_age = age;
	}
	pair<string, int> get_info()
	{
		return pair<string, int>(m_name, m_age);	// 匿名对组
	}
private:
	string m_name;
	int m_age;
};

void print_map(map<string, int>& mp)
{
	for (auto i_mp : mp)
	{
		cout << i_mp.first << " ," << i_mp.second << endl;
	}
}

void test01()
{
	// pair作为函数的返回值
	Student st1("张三", 18);
	pair<string, int> p1 = st1.get_info();
	cout << "p1.first: " << p1.first << ", p1.second: " << p1.second << endl;

	// pair作为键值对
	map<string, int> mp1;
	mp1.insert(pair<string, int>("李四", 19));		// 匿名对组
	mp1.insert(pair<string, int>("王五", 22));		// 匿名对组
	print_map(mp1);
}
int main()
{
	test01();
	system("pause");
	return 0;
}

result:
p1.first: 张三, p1.second: 18
李四 ,19
王五 ,22
相关推荐
liuyunshengsir6 分钟前
golang 中 make 和 new 的区别?
开发语言·后端·golang
猫猫头有亿点炸9 分钟前
C语言for循环嵌套if相关题目
c语言·开发语言
努力学习的小廉30 分钟前
【C++】 —— 笔试刷题day_13
开发语言·c++·哈希算法
froginwe1137 分钟前
C# 常量
开发语言
chenchihwen1 小时前
Python合并多个pdf
开发语言·python·pdf
Eiceblue1 小时前
C# 设置Excel中文本的对齐方式、换行、和旋转
开发语言·c#·excel
储悠然1 小时前
Pascal语言的区块链
开发语言·后端·golang
阿巴~阿巴~1 小时前
蓝桥杯速成刷题清单(上)
c语言·c++·算法·蓝桥杯
海风极客1 小时前
这是一份简单优雅的Prompt Engineering教程
开发语言·prompt
ChoSeitaku1 小时前
NO.84十六届蓝桥杯备战|动态规划-路径类DP|矩阵的最小路径和|迷雾森林|过河卒|方格取数(C++)
c++·矩阵·蓝桥杯