C++算法swap()函数交换或说互换引用下的两个集合的值。
template<class T> void swap(T& a, T& b);
a :这是第一个具有一定价值的集合。
b :这是另一个具有一定价值的集合。
该函数仅交换两个集合的值,并且不返回任何内容。
#include <iostream> #include <algorithm> #include <vector> int main () { int a=14, b=9; std::swap(a,b); std::vector<int> sg (4,a), ss (6,b); std::swap(sg,ss); std::cout << "sg contains:"; for (std::vector<int>::iterator ti=sg.begin(); ti!=sg.end(); ti++) std::cout << ' ' << *ti; std::cout << '\n'; return 0; }
输出:
sg contains: 14 14 14 14 14 14
#include <bits/stdc++.h> using namespace std; int main() { int ss = 9; int sg = 14; cout << "Value of ss before swapping: " << ss << endl; cout << "Value of sg before swapping: " << sg << endl; swap(ss, sg); cout << "Value of ss after swapping: " << ss << endl; cout << "Value of sg after swapping: " << sg << endl; return 0; }
输出:
Value of ss before swapping: 9 Value of sg before swapping: 14 Value of ss after swapping: 14 Value of sg after swapping: 9
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)