Namespaces
Variants

std::ranges:: swap_ranges, std::ranges:: swap_ranges_result

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더에 정의됨 <algorithm>
호출 서명
template < std:: input_iterator I1, std:: sentinel_for < I1 > S1,

std:: input_iterator I2, std:: sentinel_for < I2 > S2 >
requires std:: indirectly_swappable < I1, I2 >
constexpr swap_ranges_result < I1, I2 >

swap_ranges ( I1 first1, S1 last1, I2 first2, S2 last2 ) ;
(1) (C++20 이후)
template < ranges:: input_range R1, ranges:: input_range R2 >

requires std:: indirectly_swappable < ranges:: iterator_t < R1 > , ranges:: iterator_t < R2 >>
constexpr swap_ranges_result < ranges:: borrowed_iterator_t < R1 > ,
ranges:: borrowed_iterator_t < R2 >>

swap_ranges ( R1 && r1, R2 && r2 ) ;
(2) (C++20 이후)
헬퍼 타입
template < class I1, class I2 >
using swap_ranges_result = ranges:: in_in_result < I1, I2 > ;
(3) (C++20 이후)
1) 첫 번째 범위 [ first1 , first1 + M ) 와 두 번째 범위 [ first2 , first2 + M ) 의 요소들을 ranges:: iter_swap ( first1 + i, first2 + i ) 를 통해 교환합니다. 여기서 M = ranges:: min ( ranges:: distance ( first1, last1 ) , ranges:: distance ( first2, last2 ) ) 입니다.
범위 [ first1 , last1 ) [ first2 , last2 ) 는 겹쳐서는 안 됩니다.
2) (1) 과 동일하지만, r1 을 첫 번째 범위로, r2 를 두 번째 범위로 사용합니다. 마치 ranges:: begin ( r1 ) first1 으로, ranges:: end ( r1 ) last1 으로, ranges:: begin ( r2 ) first2 으로, ranges:: end ( r2 ) last2 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first1, last1 - 교환할 첫 번째 범위 를 정의하는 반복자-감시자 쌍
first2, last2 - 교환할 두 번째 범위 를 정의하는 반복자-감시자 쌍
r1 - 교환할 첫 번째 요소 범위
r2 - 교환할 두 번째 요소 범위

반환값

{ first1 + M, first2 + M } .

복잡도

정확히 M 번의 교환.

참고 사항

구현체들(예: MSVC STL )은 반복자 타입이 contiguous_iterator 를 모델링하고 해당 값 타입의 스왑 연산이 비트리비얼 특수 멤버 함수나 ADL 에서 발견된 swap 을 호출하지 않을 때 벡터화를 활성화할 수 있습니다.

가능한 구현

struct swap_ranges_fn
{
    template<std::input_iterator I1, std::sentinel_for<I1> S1,
             std::input_iterator I2, std::sentinel_for<I2> S2>
    requires std::indirectly_swappable<I1, I2>
    constexpr ranges::swap_ranges_result<I1, I2>
        operator()(I1 first1, S1 last1, I2 first2, S2 last2) const
    {
        for (; !(first1 == last1 or first2 == last2); ++first1, ++first2)
            ranges::iter_swap(first1, first2);
        return {std::move(first1), std::move(first2)};
    }
    template<ranges::input_range R1, ranges::input_range R2>
    requires std::indirectly_swappable<ranges::iterator_t<R1>, ranges::iterator_t<R2>>
    constexpr ranges::swap_ranges_result<ranges::borrowed_iterator_t<R1>,
                                         ranges::borrowed_iterator_t<R2>>
        operator()(R1&& r1, R2&& r2) const
    {
        return (*this)(ranges::begin(r1), ranges::end(r1),
                       ranges::begin(r2), ranges::end(r2));
    }
};
inline constexpr swap_ranges_fn swap_ranges {};
**참고:** 제공된 HTML 코드 블록 내의 모든 텍스트는 C++ 코드와 HTML 태그로 구성되어 있으며, 요청에 따라: - HTML 태그와 속성은 번역하지 않음 - ` `, `
`, `` 태그 내의 텍스트는 번역하지 않음  
- C++ 관련 용어는 번역하지 않음
따라서 번역할 일반 텍스트가 존재하지 않습니다. 코드 블록은 원본 그대로 유지됩니다.

예제

#include <algorithm>
#include <iostream>
#include <list>
#include <string_view>
#include <vector>
auto print(std::string_view name, auto const& seq, std::string_view term = "\n")
{
    std::cout << name << " : ";
    for (const auto& elem : seq)
        std::cout << elem << ' ';
    std::cout << term;
}
int main()
{
    std::vector<char> p {'A', 'B', 'C', 'D', 'E'};
    std::list<char> q {'1', '2', '3', '4', '5', '6'};
    print("p", p);
    print("q", q, "\n\n");
    // p[0, 2)와 q[1, 3) 교환:
    std::ranges::swap_ranges(p.begin(),
                             p.begin() + 4,
                             std::ranges::next(q.begin(), 1),
                             std::ranges::next(q.begin(), 3));
    print("p", p);
    print("q", q, "\n\n");
    // p[0, 5)와 q[0, 5) 교환:
    std::ranges::swap_ranges(p, q);
    print("p", p);
    print("q", q);
}

출력:

p : A B C D E
q : 1 2 3 4 5 6
p : 2 3 C D E
q : 1 A B 4 5 6
p : 1 A B 4 5
q : 2 3 C D E 6

참고 항목

(C++20)
역참조 가능한 두 객체가 참조하는 값을 교환
(customization point object)
두 객체의 값을 교환
(customization point object)
두 요소 범위를 교환
(function template)
두 반복자가 가리키는 요소를 교환
(function template)
두 객체의 값을 교환
(function template)