c++ pair

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

pair的定义如下:

cpp 复制代码
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的示例用法:

cpp 复制代码
#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对象、访问成员变量、修改成员变量以及交换对象值的操作。

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

相关推荐
DXCcn几秒前
「DAOI R1」Magic
c++
@liu6663 分钟前
码蹄集 数树
数据结构·c++·算法
5G微创业11 分钟前
免费制作证件照的小程序源码
java·开发语言·windows
jingling55534 分钟前
后端开发刷题 | 最小的K个数(优先队列)
java·开发语言·数据结构·算法
终末圆37 分钟前
探索RESTful风格的网络请求:构建高效、可维护的API接口【后端 20】
java·开发语言·数据库·后端·mysql·算法·restful
晨曦_子画43 分钟前
智能网络载入:通过 AI 和自动化彻底改变连接
服务器·开发语言·ai
小米里的大麦44 分钟前
【C++】关键字auto详解
c++·笔记·auto·自动识别类型
请揣满RMB1 小时前
Qt窗口——QMenuBar
开发语言·qt·命令模式
好想有猫猫1 小时前
【Git】远程仓库
linux·c++·git·ubuntu
program-learner1 小时前
日志系统第二弹:设计模式介绍,C和C++不定参函数的介绍
c++·设计模式·项目·日志系统