您的位置:首页 > 编程语言

枚举数组中所有可能排列的代码实现 [2004年7月8日 1:57 ]

2004-07-11 04:06 751 查看
在做数据查询的模块,想一个常常会遇到的问题,就是查询的时候经常适应各种排序的要求,一般的做法是,放上一个控件,比如ComboBox,然后上面写上
按照时间排序
按照名称排序
........................
这样要是有多个字段同时排序(eg. order by uname, tdate)的时候,要考虑多次,放的控件也要多个,代码更是累赘,怎么样才能一次代码就能适合各种场合的使用呢?这就用到在这里说到的:
             枚举数组中所有可能的排列。
这和上面说到的有什么关系呢?思路是这样:
1。定义个数组:里面是所有需要排序字段名称的集合
eg.  {“serialno“,“ratedate“,“cycode“}
2。枚举这个数组,这就意味着这个数组构成了一个树,不是吗?且来看看:
ROOT
   |--serialno
   |      |--ratedate
   |      |     |--cycode          //serialno,ratedate,cycode
   |      |
   |      |--cycode
   |            |--ratedate        //serialno,cycode,ratedate
   |--ratedate
   |      |--cycode
   |      |     |--serialno        //ratedate,cycode,serialno
   |      |
   |      |--serialno
   |            |--cycode        //ratedate,serialno,cycode
   |--cycode
          |--serialno
          |     |--ratedate      //cycode,serialno,ratedate
          |
          |--ratedate
                |--serialno       //cycode,ratedate,serialno
这样只要点击其中一个节点,一直GetParent上去,就一定能找到一个独一无二的路径,并且不会有节点重复(也就是字段拉)。
3。真正使用的时候,考虑为了不占窗体空间,可以使用快捷菜单,按照上面的树布置菜单节点,这样有个缺点,就是不能只选择其中一段作为排序路径,比如必须这样order by cycode,ratedate,serialno ,而不能order by cycode,ratedate 。因为是菜单阿!只有到了叶子才能点击。奢侈一点,就可以直接用TreeCtrl了,这样每个节点都有点击事件,也就是说,可以选取其中部分排序了。
下面代码使用TreeCtrl做。
#define ITEM_COUNT 5
const char item[ITEM_COUNT][20]={"AA","BB","CC","DD","EE"};
//strPath 从根节点到父节点的路径信息,index 当前应插入的节点索引
bool IsInPath(CString strPath,int index)
{//这个函数判断要插入的节点是否已经在路径中
 TRACE("%s_____%s/n",strPath.GetBuffer(0),&item2[index]);
        strPath.ReleaseBuffer();
 int n = strPath.Find((char*)&item2[index]);
 if(strPath.Find((char*)&item2[index])>=0)
  return true;
 else
  return false;
}
void TestInserItem(CTreeCtrl* treeCtrl,HTREEITEM hParent,int from,int count,CString strPath)
{//hParent父节点 ,from 在数组中的起始索引, count 插入个数(进入下一级个数-1)
 //strPath路径
 from=from%ITEM_COUNT;
 int j=from;
 for(int i=from;i<count+from;i++,j++)
 {
  if(j>=ITEM_COUNT)
   j=0;
  while(IsInPath(strPath,j))
  {//注意不要越界
   j++;
   j=j%ITEM_COUNT;
  }
  HTREEITEM hCurr;
  TVINSERTSTRUCT tvInsert;
  tvInsert.hParent = hParent;
  tvInsert.hInsertAfter = NULL;
  tvInsert.item.mask = TVIF_TEXT;
  tvInsert.item.pszText = (char*)&item[j];
  hCurr = treeCtrl->InsertItem(&tvInsert);
  TestInserItem(treeCtrl,hCurr,i+1,count-1,strPath+(char*)&item[j]);
 }
}
 str = "ROOT";
 tvInsert.hParent = NULL;
 tvInsert.hInsertAfter = NULL;
 tvInsert.item.mask = TVIF_TEXT;
 tvInsert.item.pszText = (LPSTR)str.GetBuffer(0);
 str.ReleaseBuffer();               //插入父节点
 HTREEITEM hRoot = treeCtrl.InsertItem(&tvInsert);
 TestInserItem(&treeCtrl,hRoot,0,ITEM_COUNT,"");
这里还有类似的实现代码
http://community.csdn.net/Expert/topic/3157/3157589.xml?temp=.6269342
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null
相关文章推荐