【问题标题】:how to sort an integer that is declared in the private如何对私有中声明的整数进行排序
【发布时间】:2012-05-01 10:36:58
【问题描述】:

我在我的类的私有部分中声明了 int id。

                    private:
                      int id,age;
                      float gpa;
                      string last,first;

此代码在我的文件中,用于显示和调用数组中的函数,并对 int id 进行排序。

        student[i].sort_array(student[i].id,cap);
        i++;
        cout << i;

这是在我放置函数的单独文件中,如果我是学生 [i].put(cout) 数据,我可以显示数组的内容。我不确定如何传入一个整数,该整数将在我的班级的 provate 部分中

        void student::sort_array(int student[i].get(id),int n)
        {

            int j,temp;
            for(j=0;j<n-1;j++)
            { 
         //if out of position switch the out of align number
            if(student[j]<student[j+1])
            {
            temp =  student[j];
            student[j] = student[j+1];
            student[j+1] = temp;
            }
         }

【问题讨论】:

  • void student::sort_array(int student[i].get(id),int n) 没有任何意义。
  • .sort_array 不应该是某个特定学生的成员。
  • 您对 C++ 的熟悉程度如何?这是作业吗?
  • 我正在尝试通过为学校编写程序来自学编程。

标签: c++ arrays sorting


【解决方案1】:

通常的方法是使用bool student::compareAges(Student const&amp; otherStudent) 方法,并将其作为额外参数传递给您的比较函数。例如。当您不使用默认 operator&lt; 时,它是 std::sort 的第三个参数

【讨论】:

  • 确实,虽然为了适合这个问题,我会说它应该是student::compareIDs。关键是你教 Student 如何将自己与另一个 Student 进行比较,这样你的排序代码就不必知道任何内部细节。
【解决方案2】:

sort_array 函数不得位于其他文件中,而应位于 Student 类声明的 .cpp 中。

而且您不必将 id 作为参数传递,因为您可以访问(即使它是私有的)它,因为您将在该类的范围内。

【讨论】:

    【解决方案3】:

    sort_array 不属于student class!对于student 的实例,“对 int id 进行排序”也没有任何意义。

    使用 C++ 标准库的std::sort() 函数对students 的集合 id 进行排序当然是可能的。

    您可以为您的student 类定义一个小于 operator,因此:

    bool student::operator <(student const& rhs) const
    {
        return id < rhs.id;
    }
    

    由于它是class 的成员,它可以访问其所有数据。

    它必须是public:,然后std::sort() 函数将能够使用它对student 的标准C++ 容器(或数组)进行排序。基于id。如果要比较class的多个属性,一定要实现strict weak ordering

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 2019-02-08
      相关资源
      最近更新 更多