首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

一个简单的对象数组 为什么无法正确排序输出呢呢呢

2013-01-07 
一个简单的对象数组 为什么无法正确排序输出呢呢呢 救命啊啊#include iostream#include stringusing n

一个简单的对象数组 为什么无法正确排序输出呢呢呢 救命啊啊
#include <iostream>
#include <string>

using namespace std;
 const int SIZE =2;
 class three;
 void show_three(three *p,int q);
class three{
  int a,b,c;
  public:
  three():a(0),b(0),c(0){}
  three(int i,int j,int k):a(i),b(j),c(k){}
  int get_a(){return a;}
  void put_date(){cout<<"please input the three number\n";
            cin>>a>>b>>c;}
  void show(){
           cout<<a<<'\t'<<b<<'\t'<<c<<endl;}
};
int main()
{

    three a[SIZE];
    for(int i=0;i<SIZE;i++)
    {
        a[i].put_date();
    }
    for(int i=0;i<SIZE-1;i++)
    for(int j=i;j<SIZE;j++)
    {
       if(a[j].get_a()>a[j+1].get_a())
       {
          swap(a[j],a[j+1]);

       }
    }
  show_three(a,SIZE);
    return 0;

}
void swap(three &a,three &b)
{
    three temp;
    temp=a;
    a=b;
    b=temp;
}
void show_three(three *p,int q)
{
    for(int i=0;i<q;i++,p++)
    {p->show();
     cout<<endl;
    }
}
[解决办法]


 for(int i=0;i<SIZE-1;i++)
    for(int j=i;j<SIZE;j++)
    {
       if(a[j].get_a()>a[j+1].get_a())
       {
          swap(a[j],a[j+1]);

       }
    }

改成

for(int i=0;i<SIZE-1;i++)
{
    for(int j=i+1;j<SIZE;j++)
    {
       if(a[i].get_a()>a[j].get_a())
       {
          swap(a[i],a[j]);

       }
    }
}

试试
[解决办法]
c++标准库函数里面有swap函数,std::swap



引用:
谢谢  懂了 为什么 开始不声明swap 也可以有结果 
#include <iostream>
#include <string>
#include<cstdlib>
using namespace std;
 const int SIZE =1224;
 class three;
 void show_three(three *p,int q);
//……

[解决办法]
楼主是不是要把每个数组还要排个序
#include <iostream>


 #include <string>
 using namespace std;
 const int SIZE =2;
 class three;
 
 void show_three(three *p,int q);
 class three{
   int a,b,c;
   public:
   three():a(0),b(0),c(0){}
   three(int i,int j,int k):a(i),b(j),c(k){}
   int get_a(){return a;} 
   void put_date(){cout<<"please input the three number\n";
             cin>>a>>b>>c;}
   void show(){
            cout<<a<<'\t'<<b<<'\t'<<c<<endl;}
   void sort();//数组排序
 };
 int main()
 {

     three a[SIZE];
     for(int i=0;i<SIZE;i++)
     {
 
         a[i].put_date();
 a[i].sort();//获得数据后排序
     }
     for( i=0;i<SIZE-1;i++)
     for(int j=i;j<SIZE;j++)
     {
        if(a[j].get_a()>a[j+1].get_a())
        {
           swap(a[j],a[j+1]);

        }
     }
   show_three(a,SIZE);
     return 0;

 }
 void swap(three &a,three &b)
 {
     three temp;
     temp=a;
     a=b;
     b=temp;
 }
 void show_three(three *p,int q)
 {
     for(int i=0;i<q;i++,p++)
     {p->show();
      cout<<endl;
     }
 }
 //排序函数
 void three::sort()
 {
 int array[]= {a,b,c}; 
 for(int i=0; i<sizeof(array)/4-1; i++)
 for(int j=i+1; j<sizeof(array)/4;j++)
 {
 if(array[i]>array[j])
 {
 int temp = array[i];
 array[i] = array[j];
 array[j] = temp;
 }
 }
     i = 0;
     a = array[i++];
 b = array[i++];
 c = array[i];

 }

热点排行