名稱空間
變體
操作

std::iter_swap

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::sort 等……
執行策略 (C++17)
排序及相關操作
劃分操作
排序操作
二分搜尋操作
(於已劃分範圍上)
集合操作(於已排序範圍上)
歸併操作(於已排序範圍上)
堆操作
最小/最大值操作
(C++11)
(C++17)
字典序比較操作
排列操作
C 庫
數值操作
未初始化記憶體上的操作
 
定義於標頭檔案 <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 的回退。

[編輯] 可能實現

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)
交換兩個可解引用物件所引用的值
(自定義點物件)[編輯]