问题分析
- 排序过程中,不可避免需要进行交换操作
- 交换的本质为数据元素间的相互复制
- 当数据元素体积庞大时,交换操作耗时是巨大的
- 解决方案:代理模式
需要访问数据元素时,通过代理序列完成
- 代码描述:
#include <iostream>
#include <ctime>
#include "Object.h"
#include "Sort.h"
using namespace std;
using namespace MyLib;
struct Test : public Object
{
int id;
int data1[1000];
double data2[500];
bool operator <(const Test& obj)
{
return id < obj.id;
}
bool operator >(const Test& obj)
{
return id > obj.id;
}
bool operator <=(const Test& obj)
{
return id <= obj.id;
}
bool operator >=(const Test& obj)
{
return id >= obj.id;
}
};
class TestProxy : public Object
{
protected:
Test* m_pTest;
public:
int id()
{
return m_pTest->id;
}
int* data1()
{
return m_pTest->data1;
}
double* data2()
{
return m_pTest->data2;
}
Test& test() const
{
return *m_pTest;
}
bool operator <(const TestProxy& obj)
{
return test() < obj.test();
}
bool operator >(const TestProxy& obj)
{
return test() > obj.test();
}
bool operator <=(const TestProxy& obj)
{
return test() <= obj.test();
}
bool operator >=(const TestProxy& obj)
{
return test() >= obj.test();
}
Test& operator =(Test& test)
{
m_pTest = &test;
return test;
}
};
Test t[1000];
TestProxy pt[1000];
int main()
{
clock_t begin;
clock_t end;
for(int i=0; i<1000; i++)
{
t[i].id = i;
pt[i] = t[i];
}
begin = clock();
Sort::Bubble(pt, 1000, true);
end = clock();
cout << "Time:" << (end - begin) << endl;
for(int i=0; i<1000; i++)
{
cout << t[i].id << " " << pt[i].id() << endl;
}
return 0;
}
(1)不使用代理时的类对象的数据排序耗时:
(2) 使用代理模式时对象的数据排序耗时:
(3)结论:排序的时间效率大幅度提高了60倍
缺点:这样的效率是付出了空间为代价的,是典型的”空间换时间”的体现