定义于头文件
算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last)
,其中 last
指代要查询或修改的最后元素的后一个元素。
std::iter_swap
template< class ForwardIt1, class ForwardIt2 > | (C++20 前) |
template< class ForwardIt1, class ForwardIt2 > | (C++20 起) |
交换给定的迭代器所指向的元素的值。
a, b | - | 指向要交换的元素的迭代器 |
类型要求 | ||
- ForwardIt1, ForwardIt2 必须满足遗留向前迭代器 (LegacyForwardIterator) 的要求。 | ||
- *a, *b 必须满足可交换 (Swappable) 的要求。 |
(无)
常数
- template<class ForwardIt1, class ForwardIt2>
- constexpr void iter_swap(ForwardIt1 a, ForwardIt2 b) // C++20 起为 constexpr
- {
- using std::swap;
- swap(*a, *b);
- }
- #include <algorithm>
- #include <functional>
- #include <iostream>
- #include <iterator>
- #include <vector>
- #include <list>
-
- struct Cell
- {
- int x;
- int y;
- Cell &operator+=(Cell &cell)
- {
- x += cell.x;
- y += cell.y;
- return *this;
- }
- };
-
- std::ostream &operator<<(std::ostream &os, const Cell &cell)
- {
- os << "{" << cell.x << "," << cell.y << "}";
- return os;
- }
-
- int main()
- {
- auto func1 = []()
- {
- static Cell cell = {99, 100};
- cell.x += 2;
- cell.y += 2;
- return cell;
- };
-
- std::vector<Cell> cells_1(6);
- std::generate_n(cells_1.begin(), cells_1.size(), func1);
- std::list<Cell> cells_2(8);
- std::generate_n(cells_2.begin(), cells_2.size(), func1);
-
- std::cout << "original : " << std::endl;
- std::cout << "cells_1 : ";
- std::copy(cells_1.begin(), cells_1.end(), std::ostream_iterator<Cell>(std::cout, " "));
- std::cout << std::endl;
- std::cout << "cells_2 : ";
- std::copy(cells_2.begin(), cells_2.end(), std::ostream_iterator<Cell>(std::cout, " "));
- std::cout << std::endl << std::endl;
-
- auto it1 = cells_1.begin();
- auto it2 = cells_2.begin();
- for (; it1 != cells_1.end(); it1++, it2++)
- {
- std::iter_swap(it1, it2);
- }
-
- std::cout << "new : " << std::endl;
- std::cout << "cells_1 : ";
- std::copy(cells_1.begin(), cells_1.end(), std::ostream_iterator<Cell>(std::cout, " "));
- std::cout << std::endl;
- std::cout << "cells_2 : ";
- std::copy(cells_2.begin(), cells_2.end(), std::ostream_iterator<Cell>(std::cout, " "));
- std::cout << std::endl << std::endl;
- }