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


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

对组的创建方式

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

访问成员

  • 使用成员属性first, second分别访问pair中的两个值。
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类型,表示的要么是键值对,要么是同时返回的两个值。

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
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值