std:swap函数在C++中的应用(附实例)

1,256 阅读3分钟

在这篇文章中,我们通过多个C++代码实例解释了std::swap函数在C++中的使用,涵盖了从原始数据类型到用户定义类。

目录:

  1. 什么是交换?
  2. 什么是C++中的std::swap?
  3. std::swap的C++代码示例

要了解交换两个变量的不同技术(超越基本技术),请阅读这篇文章。这是一篇必读的文章。

什么是互换?

交换指的是两个或多个对象的交换。在编程中,数据可以在两个变量之间互换。在现实生活中,对象可能会在两个人之间交换。

什么是C++中的std::swap?

std::swap是C++标准模板库(STL)的一个内置函数,可以交换两个变量、向量或对象。

语法:

std::swap(a,b)

:: 是C++中的范围解析操作符

要直接使用swap而不是使用std,我们需要像设置命名空间std一样:

using namespace std;
swap(a, b);

参数:这个函数需要两个参数,这是必须的。尽管参数可以有任何数据类型;但两个参数必须有相同的数据类型。

返回值:无

std::swap的C++代码示例

交换两个变量

在这个C++代码例子中,我们用swap函数交换了两个整数变量a和b,注意变量a和b的值是交换的。

using namespace std;
int main()
{
	int a = 5;
	int b = 10;

	cout<<"Values before swapping: \n";
	cout<<"a = "<<a<<endl;
	cout<<"b = "<<b<<endl;

	swap(a,b);

	cout<<"Values after swapping: \n";
	cout<<"a = "<<a<<endl;
	cout<<"b = "<<b<<endl;

} 

输出:

Values before swapping: 
a = 5
b = 10
Values after swapping: 
a = 10
b = 5

时间复杂度:O(1)

交换两个对象

在这个C++代码例子中,我们有用户定义的类Student的对象,有两个数据成员。我们使用交换函数来交换两个学生对象。请注意,所有数据成员的值都被交换了:

using namespace std;
class student {
public:
    int roll, age;

    student()
    {
        roll = 0;
        age = 0;
    }
    student(int r, int a)
    {
        roll = r;
        age = a;
    }
};

void print(student s)
{

    cout << "Roll: " << s.roll<<"\t";
    cout << "Age: " << s.age<<"\n";
}

int main()
{
	Fast_IO();
	
	student a(1, 8);
    student b(2, 10);

    cout << "Object before swapping:\n";
    cout << "Student a:\n";
    print(a);
    cout << "Student b:\n";
    print(b);

    //swap now
    swap(a, b);

    cout << "\nObject after swapping:\n";
    cout << "Student a:\n";
    print(a);
    cout << "Student b:\n";
    print(b);
}

输出:

Object before swapping:
Student a:
Roll: 1	Age: 8
Student b:
Roll: 2	Age: 10

Object after swapping:
Student a:
Roll: 2	Age: 10
Student b:
Roll: 1	Age: 8

时间复杂度:O(1)

这需要恒定的时间,因为在这种情况下,用户定义的类的数据成员数量是有限的。

交换两个数组

在这个C++代码例子中,我们使用swap函数来交换两个数组。请注意,每个索引的值都被交换了:

using namespace std;
int main()
{
	Fast_IO();
	
	int a[] = {5,4,3,2};
	int b[] = {10,11,12,13};

	cout<<"Values before swapping: \n";
	cout<<"Array a : \t";
	for(int i=0;i<4;i++){
		cout<<a[i]<<"\t";
	}
	cout<<"\nArray b : \t";
	for(int i=0;i<4;i++){
		cout<<b[i]<<"\t";
	}

	swap(a,b);

	cout<<"\n\nValues after swapping: \n";
	cout<<"Array a = \t";
	for(int i=0;i<4;i++){
		cout<<a[i]<<"\t";
	}
	cout<<"\nArray b = \t";
	for(int i=0;i<4;i++){
		cout<<b[i]<<"\t";
	}

} 

输出:

Values before swapping: 
Array a : 	5	4	3	2	
Array b : 	10	11	12	13	

Values after swapping: 
Array a = 	10	11	12	13	
Array b = 	5	4	3	2	

时间复杂度:O(N)

这需要线性时间O(N),因为数组中的所有值都被一个一个地交换了。

问题

给你两个数组A = {1,2,3,4,5}和B = {19,20,1}。当你使用C++ STL swap()交换它们时,输出结果会是什么?

错误:对'swap'的调用没有匹配的函数

A = {19,20,1},B = {1,2,3,4,5}。

分段故障(SIGSEGV)

由于两个数组的大小不同,较小的数组不能容纳较大数组的所有元素。

通过OpenGenus的这篇文章,你将拥有在C++中使用交换函数的完整知识。