C++ Algorithm 库 - iter_swap() 函数
描述
C++ 函数 std::algorithm::iter_swap() 交换两个迭代器指向的对象的值。 它使用函数 swap (unqualified) 来交换元素。
声明
以下是 std::algorithm::iter_swap() 函数形式 std::algorithm 头的声明。
C++98
template <class ForwardIterator1, class ForwardIterator2> void iter_swap (ForwardIterator1 a, ForwardIterator2 b);
参数
a − 第一个前向迭代器对象。
b − 第二个前向迭代器对象。
返回值
None
异常
如果 swap 函数抛出异常,则抛出异常。
请注意,无效参数会导致未定义的行为。
时间复杂度
Constant.
示例
以下示例显示了 std::algorithm::iter_swap() 函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {10, 20, 30, 40, 50};
iter_swap(v1.begin(), v2.begin());
iter_swap(v1.begin() + 1, v2.begin() + 2);
cout << "Vector v2 contains following elements" << endl;
for (auto it = v2.begin(); it != v2.end(); ++it)
cout << *it << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Vector v2 contains following elements 1 20 2 40 50

