C++STL算法篇swap交换算法

函数swap()用来交换两对象的值,其泛型版本定义于algorithm头文件中,使用时需要打开命名空间std。

 template<class T>
 inline void swap(T&a,T&b)
 {
    T temp(a);
    a=b;
    b=tmp;
 }

注意:swap()中T所依赖的构造函数和赋值操作行为存在,这个调用才可能有效。

swap()最大优势在于,通过模板特化或函数重载,我们可以为更复杂的型别提供特殊的实作版本;我们可以交换对象内部成员,大大地节约时间

//例如我们要交换两个A 对象的类内数据成员a,x
class A
{
private:
	int a;
	int b;
	string x;

public:
	A(int i = 0, int j = 0, string k = " ") :a(i), b(j), x(k) {}

	void swap(A& T)
	{
		using std::swap;
		swap(a, T.a);
		swap(x, T.x);
	}

	void show()
	{
		cout << a << ' ' << b << ' ' << x << endl;
	}
};


int main()
{
	A t1(1, 2, "mjh");
	A t2(3, 4, "hjm");
	t1.show();
	t2.show();

	t1.swap(t2);
	t1.show();
	t2.show();
}
原创文章 23 获赞 1 访问量 369

猜你喜欢

转载自blog.csdn.net/weixin_44806268/article/details/105553636