如何按照类中的某个属性值进行排序

来源:互联网 发布:linux解压tar.bz2命令 编辑:程序博客网 时间:2024/06/06 13:12


5分钟改的一个模板,方便以后参考使用



#include <iostream>#include<time.h>using namespace std;class card{public:int getF(){return f;}int getS(){return s;}card(int n){ f = n; s = n*2;}void setF(int newf){f = newf;}void setS(int news){ s = news;}private:int f;int s;};void Bubble(card *array, int n)//bubble sort冒泡排序{int permutation = 1;   //permutation 意为排序int k = n - 1, j;card tmp (0);while ((k >= 1) && (permutation == 1)){permutation = 0;for (j = 0; j < k; j++){if (array[j].getF()>array[j + 1].getF())  //按照card类中的f属性来排序,小在前{tmp.setF(array[j].getF());// tmp = array[j];tmp.setS(array[j].getS());//array[j] = array[j + 1];array[j].setF(array[j+1].getF());array[j].setS(array[j+1].getF());//array[j + 1] = *tmp;array[j+1].setF(tmp.getF());array[j+1].setS(tmp.getS());permutation = 1;}}k = k - 1;}}int main() {card c[7]={1,2,34,23,5,6,7};Bubble(c,7);for(int i=0;i<7;i++){cout<<c[i].getF()<<" ";}cout<<endl;for(int i=0;i<7;i++){cout<<c[i].getS()<<" ";}return 0;}


输出:

1 2 5 6 7 23 34 
2 4 5 6 7 23 68 

0 0
原创粉丝点击