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
相关推荐
hewence112 分钟前
Kotlin CoroutineContext 详解
android·开发语言·kotlin
IvanCodes12 分钟前
七、C语言指针
c语言·开发语言
寻寻觅觅☆17 分钟前
东华OJ-基础题-120-顺序的分数(C++)
开发语言·c++·算法
云小逸18 分钟前
【Vscode插件开发教程】VSCode插件开发入门指南:从C++开发者的视角
c++·ide·vscode
Myosotis51324 分钟前
作业 第三次
开发语言·python
学编程的闹钟24 分钟前
C语言WSAGetLastError函数
c语言·开发语言·学习
汉克老师25 分钟前
GESP2024年12月认证C++二级( 第二部分判断题(1-10))
c++·循环结构·分支结构·gesp二级·gesp2级
阿里嘎多学长29 分钟前
2026-02-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Ronin30540 分钟前
虚拟机数据管理模块
开发语言·c++·rabbitmq
3GPP仿真实验室41 分钟前
【Matlab源码】6G候选波形:MIMO-OFDM-IM 增强仿真平台
开发语言·网络·matlab