std::iter_swap
来自 cppreference.cn
定义于头文件 <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) |
交换两个可解引用对象所引用的值 (自定义点对象) |