📄 subject_32972.htm
字号:
<p>
序号:32972 发表者:傅杰 发表日期:2003-03-17 00:16:44
<br>主题:求助-模板排序
<br>内容:我想把模板和qsort函数联合生成一个可以对任意类型数组排序的函数,程序如下所示:<BR><BR>#include <search.h><BR>#include <stdlib.h><BR>#include <iostream.h><BR><BR>int compare( const void *arg1, const void *arg2);<BR>template <class SortT><BR>void MySort(SortT* OrgArray,int n)<BR>{<BR> qsort((void*)OrgArray,n,sizeof(SortT),compare);<BR>}<BR>template <class SortT><BR>int compare( const void *arg1, const void *arg2)<BR>{<BR> return (int)(*(SortT*)arg1)-*(SortT*)arg2);<BR>}<BR>void main(int argc, char* argv[])<BR>{<BR> int iArray[]={5,4,7,10,23,36};<BR> double dArray[]={23.5,87.3,0,-45.7,23.9,-2.5};<BR> MySort(iArray,6);<BR> MySort(dArray,6);<BR>}<BR><BR>程序的错误如下:<BR>tmplatesort.obj : error LNK2001: unresolved external symbol "int __cdecl compare(void const *,void const *)" (?compare@@YAHPBX0@Z)<BR>Debug/tmplatesort.exe : fatal error LNK1120: 1 unresolved externals<BR>Error executing link.exe.<BR><BR>但如果我交换compare和模板的声明,它又会提示SortT没有定义。不知道如何更改才能写成满足对任意类型数组排序的模板函数。
<br><a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p>
<hr size=1>
<blockquote><p>
<font color=red>答案被接受</font><br>回复者:mr_oydy 回复日期:2003-03-17 19:03:38
<br>内容://程序修改如下:<BR>#include <search.h><BR>#include <stdlib.h><BR>#include <iostream.h><BR><BR><BR>template <class SortT><BR>class Compare{<BR>typedef int (*FUNC)(const void*, const void*);<BR>static int compare( const void *arg1, const void *arg2){<BR> return (int)(*(SortT*)arg1)-(*(SortT*)arg2);<BR>}<BR>public:<BR> operator FUNC(){return compare;}<BR>};<BR><BR>template <class SortT><BR>void MySort(SortT* OrgArray,int n){<BR> qsort((void*)OrgArray,<BR> n,<BR> sizeof(SortT), <BR> Compare<SortT>());<BR>}<BR><BR><BR><BR>#define ArrLen(Name) sizeof(Name)/sizeof(Name[0])<BR><BR>void main(int argc, char* argv[]){<BR> int iArray[]={5,4,7,10,23,36};<BR> double dArray[]={23.5,87.3,0,-45.7,23.9,-2.5};<BR> MySort(iArray,6);<BR> MySort(dArray,6);<BR><BR> int i;<BR> for(i=0;i<ArrLen(iArray); i++)<BR> cout << iArray[i] << '\t';<BR> cout << endl;<BR> for(i=0; i<ArrLen(dArray); i++)<BR> cout << dArray[i] << '\t';<BR> cout << endl;<BR>}
<br>
<a href="javascript:history.go(-1)">返回上页</a><br><a href=http://www.copathway.com/cndevforum/>访问论坛</a></p></blockquote>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -