algorithm_swap_ranges

algorithm_swap_ranges (범위 교환)

std::swap_ranges는 두 범위의 요소들을 서로 교환해요. 첫 번째 범위의 각 요소를 두 번째 범위의 대응 요소와 바꿔요.

출처: cppreference

본문

std::swap_ranges는 두 범위 [first1, last1)[first2, std::next(first2, std::distance(first1, last1))) 사이의 요소들을 교환해요. <algorithm> 헤더에 정의되어 있어요.

template< class ForwardIt1, class ForwardIt2 >
ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1,
                        ForwardIt2 first2 );

병렬 실행 정책을 받는 오버로드도 있어요. 두 범위가 겹치거나 대응 반복자 쌍이 Swappable하지 않으면 동작이 정의되지 않아요.

반환값 (Return value)

두 번째 범위의 끝(past-the-end) 반복자예요.

복잡도 (Complexity)

정확히 std::distance(first1, last1)번의 스왑이 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5};
    std::vector<int> w{10, 20, 30};

    std::swap_ranges(v.begin() + 1, v.begin() + 3, w.begin());
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
    for (int x : w) std::cout << x << ' ';
    std::cout << '\n';
}

출력:

1 10 20 4 5
2 3 30

더 알아보기 (Learn more)

cppreference