Namespaces
Variants

std:: iter_swap

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
iter_swap
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
헤더 파일에 정의됨 <algorithm>
template < class ForwardIt1, class ForwardIt2 >
void iter_swap ( ForwardIt1 a, ForwardIt2 b ) ;
(C++20부터 constexpr)

주어진 반복자가 가리키는 요소들의 값을 교환합니다.

다음 조건 중 하나라도 충족되면, 동작은 정의되지 않습니다:

목차

매개변수

a, b - 교환할 요소에 대한 반복자
타입 요구사항
-
ForwardIt1, ForwardIt2 LegacyForwardIterator 요구사항을 충족해야 합니다.

반환값

(없음)

복잡도

상수.

참고 사항

이 함수 템플릿은 Swappable 에서 정의된 swap 연산의 의미론을 모델링합니다. 즉, ADL 에 의해 발견된 swap 오버로드와 std::swap 의 폴백(fallback)이 고려됩니다.

가능한 구현

template<class ForwardIt1, class ForwardIt2>
constexpr //< since C++20
void iter_swap(ForwardIt1 a, ForwardIt2 b)
{
    using std::swap;
    swap(*a, *b);
}

예제

다음은 C++에서 선택 정렬의 구현입니다.

#include <algorithm>
#include <iostream>
#include <random>
#include <string_view>
#include <vector>
template<class ForwardIt>
void selection_sort(ForwardIt begin, ForwardIt end)
{
    for (ForwardIt it = begin; it != end; ++it)
        std::iter_swap(it, std::min_element(it, end));
}
void println(std::string_view rem, std::vector<int> const& v)
{
    std::cout << rem;
    for (int e : v)
        std::cout << e << ' ';
    std::cout << '\n';
}
template<int min, int max>
int rand_int()
{
    static std::uniform_int_distribution dist(min, max);
    static std::mt19937 gen(std::random_device{}());
    return dist(gen);
}
int main()
{
    std::vector<int> v;
    std::generate_n(std::back_inserter(v), 20, rand_int<-9, +9>);
    std::cout << std::showpos;
    println("Before sort: ", v);
    selection_sort(v.begin(), v.end());
    println("After sort:  ", v);
}

가능한 출력:

Before sort: -9 -3 +2 -8 +0 -1 +8 -4 -5 +1 -4 -5 +4 -9 -8 -6 -6 +8 -4 -6 
After sort:  -9 -9 -8 -8 -6 -6 -6 -5 -5 -4 -4 -4 -3 -1 +0 +1 +2 +4 +8 +8

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 187 C++98 swap 사용 여부가 명시되지 않았음 효과는 swap ( * a, * b ) 와 동등함

참고 항목

두 객체의 값을 교환
(함수 템플릿)
두 요소 범위를 교환
(함수 템플릿)
(C++20)
조정된 두 기본 반복자가 가리키는 객체를 교환
(함수 템플릿)
(C++20)
두 기본 반복자가 가리키는 객체를 교환
(함수 템플릿)
(C++20)
두 역참조 가능 객체가 참조하는 값을 교환
(커스터마이제이션 포인트 객체)