C++常见用法——pair和make_pair
2021/11/3 11:10:10
本文主要是介绍C++常见用法——pair和make_pair,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、相同点
pair和make_pair的主要作用都是将两个数据组合成一个数据,两个数据可以是同一个类型或者不同类型。
二、区别
- pair实际上是一个结构体,其主要的两个成员变量是first和second,这两个变量可以直接使用。
伪代码如下: first = pair.first second= pair.second
- 一般make_pair都使用在需要pair做参数的位置,可以直接调用make_pair生成pair对象。
伪代码如下: pair <string,double> product3; product3 = make_pair ("shoes",20.0);
三、 pair和make_pair应用实例
#include <iostream> #include <utility> #include <string> using namespace std; int main () { pair <string,double> product1 ("tomatoes",3.25); pair <string,double> product2; pair <string,double> product3; product2.first = "lightbulbs"; // type of first is string product2.second = 0.99; // type of second is double product3 = make_pair ("shoes",20.0); cout << "The price of " << product1.first << " is $" << product1.second << "\n"; cout << "The price of " << product2.first << " is $" << product2.second << "\n"; cout << "The price of " << product3.first << " is $" << product3.second << "\n"; return 0; }
四、pair和make_pair定义
// TEMPLATE STRUCT pair template<class _Ty1,class _Ty2> struct pair { // store a pair of values typedef pair<_Ty1, _Ty2> _Myt; typedef _Ty1 first_type; typedef _Ty2 second_type; pair(): first(_Ty1()), second(_Ty2()){ // construct from defaults } pair(const _Ty1& _Val1, const _Ty2& _Val2): first(_Val1), second(_Val2){ // construct from specified values } template<class _Other1, class _Other2> pair(const pair<_Other1, _Other2>& _Right) : first(_Right.first), second(_Right.second){ // construct from compatible pair } void swap(_Myt& _Right){ // exchange contents with _Right std::swap(first, _Right.first); std::swap(second, _Right.second); } _Ty1 first; // the first stored value _Ty2 second; // the second stored value }; template<class _Ty1,class _Ty2> inline pair<_Ty1, _Ty2> make_pair(_Ty1 _Val1, _Ty2 _Val2){ // return pair composed from arguments return (pair<_Ty1, _Ty2>(_Val1, _Val2)); }
这篇关于C++常见用法——pair和make_pair的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-07Dify + TiDB Vector,快速构建你的AI Agent
- 2024-07-06有没有什么开源的py项目可以对图像进行分类-icode9专业技术文章分享
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享