转自:http://blog.youkuaiyun.com/feixiaoxing/article/details/6802182
泛型编程其实不难。本质上说,泛型编程就是让通用的算法应用到所有的数据类型。具体来说,int是我们熟悉的整数类型。那么一般情况下,如果我们写一个int整数的排序算法,应该怎么写呢?大家可以自己试试?下面的代码是我的一个范例;
- void bubble_sort(int array[], int length)
- {
- int temp = 0;
- int outer = 0;
- int inner = 0;
- assert(NULL != array && 0 != length);
- for(outer = length -1; outer >= 1; outer --)
- {
- for(inner = 0; inner <= outer; inner ++)
- {
- if(array[inner] > array[inner + 1])
- {
- temp = array[inner];
- array[inner] = array[inner + 1];
- array[inner + 1] = temp;
- }
- }
- }
- return;
- }
- class type
- {
- int data;
- public:
- type(int value = 0): data(value) {}
- type(type& t) {data = t.get_data();}
- ~type() {}
- type& operator=(type& t) {data = t.get_data(); return *this;}
- int get_data() {return data;}
- };
- int type_compare(type& t1, type& t2)
- {
- return t1.get_data() > t2.get_data() ? 1 : 0;
- }
- template <typename data>
- void bubble_sort(data array[], int length, int (*compare)(data& , data& ))
- {
- data temp;
- int outer = 0;
- int inner = 0;
- assert(NULL != array && 0 != length);
- for(outer = length -1; outer >= 1; outer --)
- {
- for(inner = 0; inner <= outer; inner ++)
- {
- if(compare(array[inner], array[inner+1]))
- {
- temp = array[inner];
- array[inner] = array[inner + 1];
- array[inner + 1] = temp;
- }
- }
- }
- return;
- }
- 272: type t[2] = {type(2), type(1)};
- 0040148D push 2
- 0040148F lea ecx,[ebp-14h]
- 00401492 call @ILT+25(type::type) (0040101e)
- 00401497 mov dword ptr [ebp-4],0
- 0040149E push 1
- 004014A0 lea ecx,[ebp-10h]
- 004014A3 call @ILT+25(type::type) (0040101e)
- 004014A8 mov byte ptr [ebp-4],1
- 273: bubble_sort<type> (t, 2, type_compare);
- 004014AC push offset @ILT+20(type_compare) (00401019)
- 004014B1 push 2
- 004014B3 lea eax,[ebp-14h]
- 004014B6 push eax
- 004014B7 call @ILT+50(bubble_sort) (00401037)
- 004014BC add esp,0Ch
- 274: return;
- 004014BF mov byte ptr [ebp-4],0
- 004014C3 lea ecx,[ebp-10h]
- 004014C6 call @ILT+5(type::~type) (0040100a)
- 004014CB mov dword ptr [ebp-4],0FFFFFFFFh
- 004014D2 lea ecx,[ebp-14h]
- 004014D5 call @ILT+5(type::~type) (0040100a)
- 275: }
问题:
(1) 大家可以尝试编写一个insert_sort的泛型函数?
(2)尝试编写一个二分法的泛型处理函数?
(3)尝试编写一个quick_sort的泛型函数,可能考虑的因素需要多一些?不过也可以尝试一下哦。
本文详细阐述了泛型编程的概念,并通过实例展示了如何将通用算法应用于各种数据类型,包括重载算术符、设计比较函数以及使用模板函数进行泛型处理。通过实例演示了如何将int整数排序算法修改为适用于通用数据类型的版本,同时提供了插入排序、二分查找和快速排序的泛型实现。最后,文章鼓励读者勇于尝试并灵活运用泛型编程技巧,以提高代码的复用性和灵活性。
2万+

被折叠的 条评论
为什么被折叠?



