WEB开发网
开发学院软件开发VC 比较数据排序前后的查找次数 阅读

比较数据排序前后的查找次数

 2007-03-16 21:57:41 来源:WEB开发网   
核心提示: class CData{public:CData();CData(int iNum, int iMax); // generate the data : _vvirtual ~CData(){};CData(const CData& rhs);void get_data(vector& v
class CData
{
public:
  CData();
  CData(int iNum, int iMax); // generate the data : _v
  virtual ~CData(){};
  CData(const CData& rhs);
  void get_data(vector& v);
protected:
  vector _v;
private:
  CData& operator=(const CData& rhs);
  const int _iMin;
};
排序数据类:class CDataSorted : public CData
{
public:
  CDataSorted(CData rhs);
  virtual ~CDataSorted(){};
private:
  CDataSorted();
  CDataSorted& operator=(const CDataSorted& rhs);
};
原始数据类:class CDataChaos : public CData
{
public:
  CDataChaos(CData rhs);
  virtual ~CDataChaos(){};
private:
  CDataChaos();
  CDataChaos& operator=(const CDataChaos& rhs);
};
查找的基类:class CFind
{
public:
  CFind(const CData& data);
  virtual ~CFind();
  virtual bool to_find(int elem, int& num);
protected:
  CData* _pdata;
private:
  CFind& operator=(const CFind& rhs);
  CFind();
};
常规查找类:class CFindWorker : public CFind
{
public:
  CFindWorker(const CData& data);
  virtual ~CFindWorker(){};
  virtual bool to_find(int elem, int& num);
private:
  CFindWorker();
};
二分查找类:class CFindBinarySearch : public CFind
{
public:
  CFindBinarySearch(const CData& data);
  virtual ~CFindBinarySearch(){};
  virtual bool to_find(int elem, int& num);
private:
  CFindBinarySearch(); // BINARY SEARCH
};
全局方法:void g_find(CFind* pFind, int elem)
{
  int num = 0;
  if ( pFind->to_find(elem, num) )
  {
    cout << "  found " << elem
      << " by " << num << " times."
      << endl;
  }
  else
  {
    cout << "  NOT found " << elem
      << " by " << num << " times!"
      << endl;
  }
  cout << endl;
}
void g_answer(CData* pData, int elem)
{
  // VC++6 IDE -- add "/GR" to settings
  if ( dynamic_cast<CDataSorted*>(pData) )
  {
    CFindBinarySearch* pBin = new CFindBinarySearch(*pData);
    g_find(pBin, elem);
    delete pBin;
  }
  else
  {
    CFindWorker* pWorker = new CFindWorker(*pData);
    g_find(pWorker, elem);
    delete pWorker;
  }
}

使用方法:CData* pData = new CData(1000, 2000);
CDataChaos* pDataChaos = new CDataChaos(*pData);
CDataSorted* pDataSorted = new CDataSorted(*pData);
cout << "/- SORTED DATA -/";
g_answer( pDataSorted, 2);
cout << "/- CHAOS DATA -/";
g_answer( pDataChaos, 2);
cout << "/- SORTED DATA -/";
g_answer( pDataSorted, 1000);
cout << "/- CHAOS DATA -/";
g_answer( pDataChaos, 1000);
delete pDataSorted;
delete pDataChaos;
delete pData;
可能的执行结果:

/- SORTED DATA -/ NOT found 2 by 10 times!

/- CHAOS DATA -/ NOT found 2 by 1000 times!

/- SORTED DATA -/ found 1000 by 10 times.

/- CHAOS DATA -/ found 1000 by 822 times.

BTW: 唉,最后还是使用了丑陋的dynamic_cast运算符,真是遗憾。我按照孟岩先生的一篇文章,在VC中装了STLport的版本,但是因为SGI-STL的map<>和微软的不同,不知道统一起来用,所以不得不暂时不用STLport的了,自己写宏么?太麻烦了,要是您有什么好办法的话,请一定写信告诉我呀。: )

上一页  1 2 

Tags:比较 数据 排序

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接