Namespaces
Variants

std::forward_list<T,Allocator>:: swap

From cppreference.net

void swap ( forward_list & other ) ;
(C++11부터)
(C++17까지)
void swap ( forward_list & other ) noexcept ( /* see below */ ) ;
(C++17부터)
(constexpr C++26부터)

컨테이너의 내용을 other 와 교환합니다. 개별 요소에 대한 이동, 복사, 교환 연산을 호출하지 않습니다.

모든 반복자와 참조는 유효하게 유지됩니다. 이 컨테이너에서 end() 값을 보유하고 있는 반복자가 작업 후 이 컨테이너를 참조할지 다른 컨테이너를 참조할지는 명시되지 않습니다.

만약 std:: allocator_traits < allocator_type > :: propagate_on_container_swap :: value true 인 경우, 할당자는 비멤버 swap 에 대한 한정되지 않은(unqualified) 호출을 사용하여 교환됩니다. 그렇지 않으면 교환되지 않으며 (만약 get_allocator ( ) ! = other. get_allocator ( ) 인 경우, 동작은 정의되지 않습니다).

목차

매개변수

other - 내용을 교환할 대상 컨테이너

예외

(없음)

(C++17까지)
noexcept 명세:
noexcept ( std:: allocator_traits < Allocator > :: is_always_equal :: value )
(C++17부터)

복잡도

상수.

예제

#include <iostream>
#include <forward_list>
template<class Os, class Co>
Os& operator<<(Os& os, const Co& co)
{
    os << '{';
    for (const auto& i : co)
        os << ' ' << i;
    return os << " } ";
}
int main()
{
    std::forward_list<int> a1{1, 2, 3}, a2{4, 5};
    auto it1 = std::next(a1.begin());
    auto it2 = std::next(a2.begin());
    int& ref1 = a1.front();
    int& ref2 = a2.front();
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
    a1.swap(a2);
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
    // swap 이후에도 반복자와 참조는 원래 연결된 요소와의 연관성을 유지합니다.
    // 예를 들어, 값 2를 가진 'a1'의 요소를 가리키던 it1은 여전히 동일한 요소를 가리키지만,
    // 이 요소는 'a2'로 이동되었습니다.
}

출력:

{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4

참고 항목

std::swap 알고리즘의 특수화
(함수 템플릿)