问题:
多关键字排序是否比单关键字排序更复杂?
对于多关键字排序,只需要在比较操作时同时考虑多个关键字即可。
和单关键字排序本质相同,并不会复杂。
多关键字比较示例程序:
1 #include <iostream> 2 #include <cstring> 3 #include "DTString.h" 4 #include "LinkList.h" 5 #include "Object.h" 6 7 using namespace std; 8 using namespace DTLib; 9 10 struct Test : public Object 11 { 12 int key1; 13 int key2; 14 15 Test(int k1, int k2) 16 { 17 key1 = k1; 18 key2 = k2; 19 } 20 21 bool operator ==(const Test& t) 22 { 23 return (key1 == t.key1) && (key2 == t.key2); 24 } 25 26 bool operator != (const Test& t) 27 { 28 return !(*this == t); 29 } 30 31 bool operator < (const Test& t) // 定义k1优先级高 32 { 33 return (key1 < t.key1) || ((key1 == t.key1) && (key2 < t.key2)); 34 } 35 36 bool operator >= (const Test& t) // 定义k1优先级高 37 { 38 return !(*this < t); 39 } 40 41 bool operator > (const Test& t) // 定义k1优先级高 42 { 43 return (key1 > t.key1) || ((key1 == t.key1) && (key2 > t.key2)); 44 } 45 46 bool operator <= (const Test& t) // 定义k1优先级高 47 { 48 return !(*this > t); 49 } 50 }; 51 52 int main() 53 { 54 Test t1(3, 4); 55 Test t2(2, 5); 56 57 cout << (t1 > t2) << endl; 58 59 return 0; 60 }
结果输出1。
这意味着我们的多关键字比较就定义好了。
Sort的构造函数、拷贝构造函数、赋值操作符全部为私有的,也就是我们不能创造Sort类的对象。这个类不可能产生对象。
我们将不同的排序法实现为这个类的静态成员函数即可。
添加Sort.h:
1 #ifndef SORT_H 2 #define SORT_H 3 4 #include "Object.h" 5 6 namespace DTLib 7 { 8 9 class Sort : public Object 10 { 11 private: 12 Sort(); 13 Sort(const Sort&); 14 Sort& operator = (const Sort&); 15 16 template <typename T> 17 static void Swap(T& a, T& b) 18 { 19 T c(a); 20 a = b; 21 b = c; 22 } 23 24 public: 25 26 }; 27 28 } 29 30 #endif // SORT_H
小结: