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
相关推荐
码上淘金40 分钟前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo43 分钟前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
虾球xz1 小时前
游戏引擎学习第268天:合并调试链表与分组
c++·学习·链表·游戏引擎
fpcc2 小时前
跟我学c++高级篇——模板元编程之十三处理逻辑
c++
格林威2 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉
橙子199110163 小时前
在 Kotlin 中什么是委托属性,简要说说其使用场景和原理
android·开发语言·kotlin
androidwork3 小时前
Kotlin Android LeakCanary内存泄漏检测实战
android·开发语言·kotlin
学地理的小胖砸3 小时前
【Python 基础语法】
开发语言·python
Dream it possible!3 小时前
LeetCode 热题 100_只出现一次的数字(96_136_简单_C++)(哈希表;哈希集合;排序+遍历;位运算)
c++·leetcode·位运算·哈希表·哈希集合
DanB245 小时前
Java笔记4
java·开发语言·笔记