【数据结构开篇】
我的数据结构比较差,所以一点点学习吧,时间不负有心人。
--------------------------------------------------------------------------------------------------------------------------------
【数据结构】 完成两个数据交换
完成两个数据的交换虽然简单,但是在实际的算法的最底层却大量使用。下面代码展示了若干种两个数据交换的实例,更重要的是 利用 std::swap(a,b) c++提供的模版类方式实现,它可以交换任何数据。
#include <iostream>
using namespace std;
//通过值传递交换
void swap(int x, int y) {
int temp;
temp = x;
x = y;
y = temp;
}
//通过引用交换
void swap1(int &x, int &y) {
int temp;
temp = x;
x = y;
y = temp;
}
//通过指针交换
void swap2(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
template<typename T>
void swap3(T& x, T& y) {
T temp;
temp = x;
x = y;
y = temp;
}
int main()
{
int a = 1;
int b = 2;
cout << "通过值传递无法完成交换" << endl;
cout << "a = " << a << " b = " << b << endl;
swap(a, b);
cout << "a = "<<a << " b = " << b << endl;
cout << "通过引用完成交换" << endl;
cout << "a = " << a << " b = " << b << endl;
swap1(a, b);
cout << "a = " << a << " b = " << b << endl;
cout << "通过指针完成交换" << endl;
cout << "a = " << a << " b = " << b << endl;
swap2(&a, &b);
cout << "a = " << a << " b = " << b << endl;
cout << "通过模版完成交换" << endl;
cout << "a = " << a << " b = " << b << endl;
std::swap(a, b);
cout << "a = " << a << " b = " << b << endl;
cout << "通过模版自定义完成交换" << endl;
cout << "a = " << a << " b = " << b << endl;
swap3(a, b);
cout << "a = " << a << " b = " << b << endl;
system("pause");
}