std::swap(std::tuple)

来自cppreference.com
< cpp‎ | utility‎ | tuple
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)
 
 
在标头 <tuple> 定义
(1)
template< class... Types >

void swap( std::tuple<Types...>& lhs,

           std::tuple<Types...>& rhs ) noexcept(/* see below */);
(C++11 起)
(C++20 前)
template< class... Types >

constexpr void swap( std::tuple<Types...>& lhs,

                     std::tuple<Types...>& rhs ) noexcept(/* see below */);
(C++20 起)
template< class... Types >

constexpr void swap( const std::tuple<Types...>& lhs,

                     const std::tuple<Types...>& rhs ) noexcept(/* see below */);
(2) (C++23 起)

交换 lhsrhs 的内容。等价于 lhs.swap(rhs)

1) 此重载只有在 std::is_swappable_v<Ti> 对从 0 到 sizeof...(Types) 的所有 i 为 true 时才会参与重载决议。
2) 此重载只有在 std::is_swappable_v<const Ti> 对从 0 到 sizeof...(Types) 的所有 i 为 true 时才会参与重载决议。
(C++17 起)

参数

lhs, rhs - 要交换内容的 tuple

返回值

(无)

异常

noexcept 说明:  
noexcept(noexcept(lhs.swap(rhs)))

示例

#include <iostream>
#include <string>
#include <tuple>
 
int main()
{
    std::tuple<int, std::string, float>
                      p1{42, "ABCD", 2.71},
                      p2;
    p2 = std::make_tuple(10, "1234", 3.14);
 
    auto print_p1_p2 = [&](auto rem) {
        std::cout << rem
                  << "p1 = {" << std::get<0>(p1)
                  << ", "     << std::get<1>(p1)
                  << ", "     << std::get<2>(p1) << "}, "
                  << "p2 = {" << std::get<0>(p2)
                  << ", "     << std::get<1>(p2)
                  << ", "     << std::get<2>(p2) << "}\n";
    };
 
    print_p1_p2("Before p1.swap(p2): ");
    p1.swap(p2);
    print_p1_p2("After  p1.swap(p2): ");
    swap(p1, p2);
    print_p1_p2("After swap(p1, p2): ");
}

输出:

Before p1.swap(p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14}
After  p1.swap(p2): p1 = {10, 1234, 3.14}, p2 = {42, ABCD, 2.71}
After swap(p1, p2): p1 = {42, ABCD, 2.71}, p2 = {10, 1234, 3.14}

参阅

交换两个 tuple 的内容
(公开成员函数)
特化 std::swap 算法
(函数模板)