std::iter_swap
来自cppreference.com
| 在标头 <algorithm> 定义
|
||
| |
(C++20 起为 constexpr) |
|
交换给定的迭代器所指向的元素的值。
如果满足以下任意条件,那么行为未定义:
a或b不可解引用。*a与*b不可交换 (Swappable) 。
参数
| a, b | - | 指向要交换的元素的迭代器 |
| 类型要求 | ||
-ForwardIt1, ForwardIt2 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
返回值
(无)
复杂度
常数。
注解
这个函数模板构成可交换 (Swappable) 给出的交换操作的语义。就是说,其会考虑由 ADL 找到的 swap,并回退于使用 std::swap。
可能的实现
template<class ForwardIt1, class ForwardIt2>
constexpr //< 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("排序前: ", v);
selection_sort(v.begin(), v.end());
println("排序后: ", v);
}
可能的输出:
排序前: -9 -3 +2 -8 +0 -1 +8 -4 -5 +1 -4 -5 +4 -9 -8 -6 -6 +8 -4 -6
排序后: -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)
|
