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
相关推荐
Love__Tay8 分钟前
【学习笔记】Python金融基础
开发语言·笔记·python·学习·金融
Lilith的AI学习日记21 分钟前
什么是预训练?深入解读大模型AI的“高考集训”
开发语言·人工智能·深度学习·神经网络·机器学习·ai编程
wangjinjin1801 小时前
Python Excel 文件处理:openpyxl 与 pandas 库完全指南
开发语言·python
愚润求学1 小时前
【C++】类型转换
开发语言·c++
@我漫长的孤独流浪1 小时前
数据结构测试模拟题(4)
数据结构·c++·算法
斯奕sky_small-BAD1 小时前
C++ if语句完全指南:从基础到工程实践
java·开发语言·php
Humbunklung1 小时前
Rust Floem UI 框架使用简介
开发语言·ui·rust
csdnzzt1 小时前
从内存角度透视现代C++关键特性
c++
jie188945758662 小时前
C++ 中的 const 知识点详解,c++和c语言区别
java·c语言·c++
网安INF2 小时前
RSA加密算法:非对称密码学的基石
java·开发语言·密码学