std::iter_swap
来自 zh.cppreference.net
| 在头文件中定义 <algorithm>
|
||
template< class ForwardIt1, class ForwardIt2 >
void iter_swap( ForwardIt1 a, ForwardIt2 b );
|
(C++20 起为 constexpr) | |
交换给定迭代器所指向元素的值。
如果满足以下任一条件,则行为未定义:
a或b不可 解引用。*a不可与 可交换 (Swappable) 的*b。
参数
| a, b | - | 指向要交换元素的迭代器 |
| 类型要求 | ||
-ForwardIt1, ForwardIt2 必须满足 老式向前迭代器 (LegacyForwardIterator) 的要求。
| ||
返回值
(无)
复杂度
常数。
注解
此函数模板模拟 可交换 (Swappable) 所描述的交换操作语义。即,考虑通过 swapADL 找到的 重载以及 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++ 标准。
| DR | 应用于 | 已发布的行为 | 正确行为 |
|---|---|---|---|
| LWG 187 | C++98 | 未指定是否使用 swap
|
效果等价于 swap(*a, *b)
|
参阅
| 交换两个对象的值 (函数模板) | |
| 交换两个元素范围 (函数模板 & 算法函数对象) | |
(C++20) |
|
(C++20) |
交换两个调整后的底层迭代器所指向的对象 (函数模板) |
(C++20) |
交换两个底层迭代器所指向的对象 (函数模板) |
(C++20) |
交换两个可解引用对象所引用的值 (定制点对象) |