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
相关推荐
C-SDN花园GGbond1 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处2 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ3 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
leon6253 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
CV工程师小林3 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice4 小时前
2024.9.19
c++
天玑y4 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
锦亦之22334 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏4 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
姜太公钓鲸2334 小时前
c++ static(详解)
开发语言·c++