0

I declared the int id in the private, part of my class.

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

This code is in my file to display and call for functions that are in the array, and to sort the int id.

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

This is in a seperate file where i put my functions, i am able to display the contents of the array, if i student[i].put(cout) the data. I am not sure how to pass in an integer that would be in the provate part of my class

        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;
            }
         }
MIkey27
  • 25
  • 1
  • 5

3 Answers3

3

The normal method is to have a bool student::compareAges(Student const& otherStudent) method, aand pass that as an extra argument to your comparison function. E.g. it's the third argument to std::sort when you're not using the default operator<

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 1
    Indeed, although to fit the question I'd say it should be `student::compareIDs`. The point being that you teach `Student` how to compare itself to another `Student` so your sorting code doesn't have to know about any internal details. – Matthew Walton May 01 '12 at 10:47
0

The sort_array function must not be in a different file but in the .cpp of your Student class decleration.

And you do not have to pass the id as a parameter since you can access (even if it is private) it because you will be in that class's scope.

phantasmagoria
  • 319
  • 1
  • 5
0

sort_array doesn't belong in the student class! Nor does it make sense "to sort the int id" for an instance of student.

Sorting a collection of students by id using the C++ standard library's std::sort() function is certainly possible.

You can define a less-than operator for your student class, thus:

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

Since it is a member of the class it can access all of its data.

It must be public:, then std::sort() function will be able to use this to sort a standard C++ container (or array) of student. based on the id. If you want to compare multiple attributes of the class, be sure to implement strict weak ordering.

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247