C++利用访函数进行选择排序
生活随笔
收集整理的這篇文章主要介紹了
C++利用访函数进行选择排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include?<iostream>??//標準輸入輸出流
using?namespace?std;//標準命名空間const?int?CMP_LES?=?-1;//定義的常量
const?int?CMP_EQU?=?0;
const?int?CMP_BIG?=?1;class?Comparer??//仿函數的類?函數的主要功能是重載運算符()這樣調用的時候就直接用類引用加上()后面的參數就可以?
{
public:Comparer(int?cmpType){m_cmpType?=?cmpType;//初始化變量}bool?operator?()(int?num1,?int?num2)?const{bool?res;switch(m_cmpType){case?CMP_LES:res?=?num1?<?num2;break;case?CMP_EQU:res?=?num1?==?num2;break;case?CMP_BIG:res?=?num1?>?num2;break;default:res?=?false;break;}return?res;}
private:int?m_cmpType;
};//互相交換數值
void?Swap(int?&num1,?int?&num2)
{int?temp?=?num1;num1?=?num2;num2?=?temp;
}//這個是個排序函數?雙層循環來排列順序?
void?SortArray(int?array[],?int?size,?const?Comparer?&cmp)
{for?(int?i?=?0;?i?<?size?-?1;?++i){int?indx?=?i;for?(int?j?=?i?+?1;?j?<?size;?++j){if?(cmp(array[indx],?array[j]))//這里是對仿函數類的引用?看看很像函數?{indx?=?j;}if?(indx?!=?i){Swap(array[i],?array[indx]);indx?=?i;?//這句必須尤其要注意,千萬不能忘了}}}
}//這是輸出顯示函數
void?ListArray(int?array[],?int?size)?
{for?(int?i?=?0;?i?<?size;?++i){cout?<<?array[i]?<<?"?";}
}#define?ARY_SIZE?10
int?main()
{int?array[ARY_SIZE]?=?{10,?12,?9,?31,?93,?34,?98,?9,?1,?20};//定義一個數組?有十個數據cout?<<?"The?initial?array?is?:?";//首先輸出現在的數組數據ListArray(array,?ARY_SIZE);cout?<<?endl;SortArray(array,?ARY_SIZE,?Comparer(CMP_BIG));//然后在這里用到了SortArray排序函數?其中第三個參數是個//對象的引用?所以要初始化這個對象(他是先初始化Comparer對象然后再動作的)cout?<<?"The?ascending?sorted?array?is?:";ListArray(array,?ARY_SIZE);cout?<<?endl;SortArray(array,?ARY_SIZE,?Comparer(CMP_LES));//用這個方法來排序cout?<<?"The?descending?sorted?array?is?:?";//輸出排序以后的方法ListArray(array,?ARY_SIZE);int?wait;cin?>>?wait;return?0;
}
轉載于:https://www.cnblogs.com/ganquanfu2008/p/3180913.html
總結
以上是生活随笔為你收集整理的C++利用访函数进行选择排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cracking the coding
- 下一篇: mysql处理存在则更新,不存在则插入(