std :: swap()
swap()是一个标准的库函数,它可以将任意两个对象交换b / w值。在C11中,它已移至标头下。以下是swap()的语法详细信息。
语法:void swap (T& a, T& b);
参数: T&a,T&b,它们是要交换的对象
返回类型: void-不返回任何内容。
用法:交换两个对象的黑白值
例子:
1)交换两种内置数据类型
在下面的示例中,我们看到如何使用std :: swap()函数交换两个整数。#include
using namespace std;
int main(){
int a = 10, b = 20;
cout <
cout <
//立即交换
swap(a, b);
cout <
cout <
return 0;
}
输出:Before swapping:
//答: 10, b: 20
After swapping:
//答: 20, b: 10
2)交换两个用户定义的对象
在下面的示例中,我们看到如何使用std :: swap()函数交换两个用户定义的对象。在这里,我们定义了一个学生类,因为我们看到交换如何在他们之间交换内容。#include
using namespace std;
class student {
public:
int roll;
string name;
int marks; student()
{
roll = -1;
name = "";
marks = 0;
}
student(int r, string s, int m)
{
roll = r;
name = s;
marks = m;
}
};
void print(student t)
{
cout <
cout <
cout <
}
int main(){
student a(1, "Alice", 80);
student b(2, "Bob", 85);
cout <
cout <
print(a);
cout <
print(b);
//立即交换
swap(a, b);
cout <
cout <
print(a);
cout <
print(b);
return 0;
}
输出:Before swapping:
Student //答:
//滚动: 1
//名称: Alice
//标记: 80
Student b:
//滚动: 2
//名称: Bob
//标记: 85
After swapping:
Student //答:
//滚动: 2
//名称: Bob
//标记: 85
Student b:
//滚动: 1
//名称: Alice
//标记: 80
3)在两个向量(容器)之间交换
在下面的示例中,我们将看到如何交换两个向量的内容。同样,我们可以交换任何容器的be / w对象。#include
using namespace std;
void print(vector a)
{
for (auto it : a) {
cout <
}
cout <
}
int main(){
vector a{ 10, 20, 30, 40 };
vector b{ 1, 2, 3, 4, 5, 6, 7 };
cout <
cout <
print(a);
cout <
print(b);
//立即交换
swap(a, b);
cout <
cout <
print(a);
cout <
print(b);
return 0;
}
输出:Before swapping:
Vector //答:
10 20 30 40
Vector b:
1 2 3 4 5 6 7
After swapping:
Vector //答:
1 2 3 4 5 6 7
Vector b:
10 20 30 40