当前位置: 首页 > article >正文

c++ pair

C++中的pair是一个模板类,用来存储两个不同类型的对象。它位于<utility>头文件中,并定义在std命名空间中。

pair的定义如下:

template <class T1, class T2>
struct pair {
    using first_type = T1;
    using second_type = T2;

    T1 first;
    T2 second;

    // 构造函数
    constexpr pair();
    constexpr pair(const T1& x, const T2& y);
    template<class U1, class U2>
    constexpr pair(U1&& x, U2&& y);
    template<class... Args1, class... Args2>
    constexpr pair(piecewise_construct_t, tuple<Args1...> first_args, tuple<Args2...> second_args);

    // 拷贝和移动构造函数
    template<class U1, class U2>
    constexpr pair(const pair<U1, U2>& other);
    template<class U1, class U2>
    constexpr pair(pair<U1, U2>&& other);

    // 赋值操作符
    template<class U1, class U2>
    constexpr pair& operator=(const pair<U1, U2>& other);
    template<class U1, class U2>
    constexpr pair& operator=(pair<U1, U2>&& other);
    constexpr void swap(pair& other) noexcept(noexcept(swap(first, other.first)) && noexcept(swap(second, other.second)));
   
};

pair提供了以下主要功能:

  • firstsecondpair的两个成员变量,用来存储两个不同类型的值。
  • pair的构造函数可以接受两个参数,并根据参数的类型自动推导为firstsecond进行初始化。
  • pair提供了拷贝和移动构造函数,以及赋值操作符,可以方便地进行对象的拷贝、移动和赋值操作。
  • pair的成员变量可以使用std::get函数或者std::tie函数进行访问和解包。
  • pair还提供了swap函数,用来交换两个pair对象的值。

以下是pair的示例用法:

#include <iostream>
#include <utility>

int main() {
    std::pair<int, std::string> p1(1, "one");
    std::pair<int, std::string> p2 = std::make_pair(2, "two");

    std::cout << p1.first << " " << p1.second << std::endl;
    std::cout << p2.first << " " << p2.second << std::endl;

    p1.second = "updated";
    std::cout << p1.first << " " << p1.second << std::endl;

    std::swap(p1, p2);
    std::cout << p1.first << " " << p1.second << std::endl;
    std::cout << p2.first << " " << p2.second << std::endl;

    return 0;
}

输出结果:

1 one
2 two
1 updated
2 updated
1 two

以上示例展示了创建pair对象、访问成员变量、修改成员变量以及交换对象值的操作。

希望以上解释对你有所帮助!如有其他问题,请随时提问。


http://www.kler.cn/news/317364.html

相关文章:

  • ubuntu下检查端口是否占用问题,编写shell脚本检查端口是否占用
  • 使用Python实现图形学曲线和曲面的NURBS算法
  • ChartLlama: A Multimodal LLM for Chart Understanding and Generation论文阅读
  • unity Compute Shaders 使程序在GPU中运行
  • LeetCode54. 螺旋矩阵(2024秋季每日一题 21)
  • 计算机毕业设计Hadoop+PySpark深圳共享单车预测系统 PyHive 共享单车数据分析可视化大屏 共享单车爬虫 共享单车数据仓库 机器学习 深度学习
  • 工博会蓝卓逛展攻略
  • C#测试调用Ghostscript.NET浏览PDF文件
  • <刷题笔记> 二叉搜索树与双向链表注意事项
  • OpenHarmony(鸿蒙南向开发)——标准系统方案之瑞芯微RK3568移植案例(上)
  • 流域碳中和技术
  • 使用Docker一键部署Blossom笔记软件
  • 【C#生态园】一文详解:NHibernate、Entity Framework Core、Dapper 等 .NET ORM 框架优劣对比
  • M9410A VXT PXI 矢量收发信机,300/600/1200MHz带宽
  • 防火墙详解(三)华为防火墙基础安全策略配置(命令行配置)
  • 11. DPO 微调示例:根据人类偏好优化LLM大语言模型
  • 【电商搜索】现代工业级电商搜索技术-Ha3搜索引擎平台简介
  • 应用层-网络协议
  • Java面试篇基础部分- Java中的阻塞队列
  • 解决selenium爬虫被浏览器检测问题
  • 5. 条件 Conditionals
  • 56 mysql 用户权限相关的实现
  • Spring高手之路24——事务类型及传播行为实战指南
  • DHCP中继工作原理
  • 算法【Dijkstra算法及分层图最短路】
  • WPF实现关系图
  • Vue开发前端图片上传给java后端
  • MMD模型一键完美导入UE5-VRM4U插件方案(一)
  • 为什么三星、OPPO、红米都在用它?联发科12nm级射频芯片的深度剖析
  • Fyne ( go跨平台GUI )中文文档-入门(一)