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

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

相关推荐
曼巴UE517 分钟前
UE5.3 C++ 接口初步使用
开发语言·jvm·c++
奔跑的石头_21 分钟前
GO语言的主要语法和特性
开发语言
泛联新安23 分钟前
如何根据项目需求选择合适的软件测试工具?iUnit智能单元测试平台提供专业化解决方案
c++·测试工具·单元测试
曙曙学编程29 分钟前
stm32——NVIC,EXIT
c语言·c++·stm32·单片机·嵌入式硬件
liulilittle37 分钟前
UNIX/macOS路由表查询原理与实现
服务器·开发语言·c++·macos·unix·编程语言
HUST1 小时前
C语言 第三讲:分支和循环(上)
c语言·开发语言
Dovis(誓平步青云)2 小时前
《探索C++11:现代语法的性能优化策略(中篇)》
开发语言·c++
再努力"亿"点点2 小时前
爬取m3u8视频完整教程
开发语言·python
一个响当当的名号2 小时前
c++primer 个人学习总结-模板和泛型编程
开发语言·c++·学习
落羽的落羽2 小时前
【C++】C++11的可变参数模板、emplace接口、类的新功能
开发语言·c++·学习