关键词:排序类和数组类的关联、代理模式
0. 排序类(Sort)与数组类(Array)的关系
新增成员函数
在Array.h中添加:
T* array() const
{
return m_array;
}
在Sort.h中添加:
template < typename T >
static void Select(Array<T>& array, bool min2max = true)
{
Select(array.array(), array.length(), min2max);
}
template < typename T >
static void Insert(Array<T>& array, bool min2max = true)
{
Insert(array.array(), array.length(), min2max);
}
template < typename T >
static void Bubble(Array<T>& array, bool min2max = true)
{
Bubble(array.array(), array.length(), min2max);
}
template < typename T >
static void Shell(Array<T>& array, bool min2max = true)
{
Shell(array.array(), array.length(), min2max);
}
template < typename T >
static void Merge(Array<T>& array, bool min2max = true)
{
Merge(array.array(), array.length(), min2max);
}
template < typename T >
static void Quick(Array<T>& array, bool min2max = true)
{
Quick(array.array(), array.length(), min2max);
}
1. 当待排数据元素为体积庞大的对象时,如何提高排序的效率?
问题分析:
- 排序过程中不可避免的需要进行交换操作
- 交换操作的本质为数据元素间的相互复制
- 当数据元素体积较大时,交换操作耗时巨大
解决方案:代理模式
- 为待排数据元素设置代理对象
- 对代理对象所组成的序列进行排序
- 需要访问有序数据元素时,通过访问代理序列完成
代理模式类图
/* -----测试代理模式的使用----- */
#include "Sort.h"
#include <ctime>
#include "Object.h"
struct Test_Proxy : public Object
{
int id;
int data1[1000];
double data2[500];
bool operator <(const Test_Proxy& obj)
{
return id < obj.id;
}
bool operator <=(const Test_Proxy& obj)
{
return id <= obj.id;
}
bool operator >(const Test_Proxy& obj)
{
return id > obj.id;
}
bool operator >=(const Test_Proxy& obj)
{
return id >= obj.id;
}
};
class Proxy : public Object
{
private:
Test_Proxy* m_pTest;
public:
int id()
{
return m_pTest->id;
}
int* data1()
{
return m_pTest->data1;
}
double* date2()
{
return m_pTest->data2;
}
Test_Proxy& test_proxy() const
{
return *m_pTest;
}
bool operator <(const Proxy& obj) // 代理类对象的比较即为原始类对象的比较
{
return test_proxy() < obj.test_proxy();
}
bool operator <=(const Proxy& obj)
{
return test_proxy() <= obj.test_proxy();
}
bool operator >(const Proxy& obj)
{
return test_proxy() > obj.test_proxy();
}
bool operator >=(const Proxy& obj)
{
return test_proxy() >= obj.test_proxy();
}
Test_Proxy& operator =(Test_Proxy& test)
{
m_pTest = &test;
return test;
}
};
Test_Proxy tp[10000];
Proxy p[10000];
void test_proxy()
{
clock_t begin = 0;
clock_t end = 0;
for(int i=0; i<10000; ++i)
{
tp[i].id = i;
p[i] = tp[i];
}
begin = clock();
Sort::Bubble(p, 10000, false);
end = clock();
cout << "time = " << end - begin << endl;
for(int i=0; i<10000; ++i)
{
cout << tp[i].id << " : " << p[i].id() << endl;
}
}
2. 小结
- DTLib中的排序类和数组类之间存在关联关系
- 排序类能够对数组类对象进行排序
- 当排序体积庞大的对象时,使用代理模式间接完成
- 代理模式的使用有效避开大对象交换时的耗时操作
- 代理模式解决方案是空间换时间思想的体现
声明:此文章仅是本人在学习狄泰学院《数据结构实战开发教程》所做的笔记,文章中包含狄泰软件资料内容,一切版权归狄泰软件所有!
实验环境:ubuntu10 + Qt Creator2.4.1 + Qt SDK 4.7.4










网友评论