项目开发中排序问题的解决方案

问题分析

  1. 排序过程中,不可避免需要进行交换操作
  2. 交换的本质为数据元素间的相互复制
  3. 当数据元素体积庞大时,交换操作耗时是巨大的
  4. 解决方案:代理模式
    需要访问数据元素时,通过代理序列完成
    这里写图片描述
  5. 代码描述:
#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倍
缺点:这样的效率是付出了空间为代价的,是典型的”空间换时间”的体现

猜你喜欢

转载自blog.csdn.net/feiyanaffection/article/details/79315986