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 的要求。

返回值

(无)

复杂度

常量。

注释

此函数模板模拟由 可交换类型 规定的交换操作语义。具体而言,会考虑通过 ADL 查找到的 swap 重载以及回退方案 std::swap

可能的实现

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++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 187 C++98 未明确说明是否使用 swap 效果等同于 swap ( * a, * b )

参见

交换两个对象的值
(函数模板)
交换两个元素范围
(函数模板)
(C++20)
交换两个已调整底层迭代器所指向的对象
(函数模板)
(C++20)
交换两个底层迭代器所指向的对象
(函数模板)
(C++20)
交换两个可解引用对象所引用的值
(定制点对象)