Namespaces
Variants

std::pair<T1,T2>:: swap

From cppreference.net
Utilities library
(1)
void swap ( pair & other ) noexcept ( /* siehe unten */ ) ;
(seit C++11)
(bis C++20)
constexpr void swap ( pair & other ) noexcept ( /* siehe unten */ ) ;
(seit C++20)
constexpr void swap ( const pair & other ) const noexcept ( /* siehe unten */ ) ;
(2) (seit C++23)

Tauscht first mit other.first und second mit other.second , als ob durch using std:: swap ; swap ( first, other. first ) ; swap ( second, other. second ) ; .

Wenn der ausgewählte swap -Funktionsaufruf fehlerhaft ist oder den Wert des Members nicht austauscht, ist das Verhalten undefiniert.

(bis C++23)
1) Das Programm ist fehlerhaft, wenn entweder std:: is_swappable_v < T1 > oder std:: is_swappable_v < T2 > nicht true ist.
2) Das Programm ist fehlerhaft, wenn entweder std:: is_swappable_v < const T1 > oder std:: is_swappable_v < const T2 > nicht true ist.

Wenn der ausgewählte swap -Funktionsaufruf den Wert des Members nicht austauscht, ist das Verhalten undefiniert.

(seit C++23)

Inhaltsverzeichnis

Parameter

other - Paar von Werten zum Austauschen

Rückgabewert

(keine)

Ausnahmen

noexcept Spezifikation:
noexcept (

noexcept ( swap ( first, other. first ) ) &&
noexcept ( swap ( second, other. second ) )

)

Im obigen Ausdruck wird der Bezeichner swap auf dieselbe Weise gesucht wie vom C++17-Merkmal std::is_nothrow_swappable verwendet.

(bis C++17)
1)
noexcept Spezifikation:
noexcept (

std:: is_nothrow_swappable_v < first_type > &&
std:: is_nothrow_swappable_v < second_type >

)
2)
noexcept Spezifikation:
noexcept (

std:: is_nothrow_swappable_v < const first_type > &&
std:: is_nothrow_swappable_v < const second_type >

)
(seit C++17)

Beispiel

#include <iostream>
#include <utility>
#include <string>
int main()
{
    std::pair<int, std::string> p1(10, "test"), p2;
    p2.swap(p1);
    std::cout << "(" << p2.first << ", " << p2.second << ")\n";
#if __cpp_lib_ranges_zip >= 202110L
    // Verwendung der C++23 const-qualifizierten Swap-Überladung
    // (swap propagiert nicht länger die Konstanz von pair)
    int i1 = 10, i2{};
    std::string s1("test"), s2;
    const std::pair<int&, std::string&> r1(i1, s1), r2(i2, s2);
    r2.swap(r1);
    std::cout << "(" << i2 << ", " << s2 << ")\n";
#endif
}

Mögliche Ausgabe:

(10, test)
(10, test)

Fehlerberichte

Die folgenden verhaltensändernden Fehlerberichte wurden rückwirkend auf zuvor veröffentlichte C++-Standards angewendet.

DR Angewendet auf Verhalten wie veröffentlicht Korrektes Verhalten
LWG 2456 C++11 die noexcept Spezifikation ist fehlerhaft funktionsfähig gemacht

Siehe auch

tauscht die Werte zweier Objekte
(Funktions-Template)
tauscht die Inhalte zweier tuple s
(öffentliche Elementfunktion von std::tuple<Types...> )