0

I have a class student with parameters Number, Name, Grade and i have functions for input and output

  void insertdata(){
        cin>>number;
        cin>>name;
        cin>>grade;
    }
    void showdata() {
        cout<<number<<" "<<name<<" "<<grade<<endl;
    }

In the main function I'm inserting the data by this way

int n,i;
cin>>n;
student a;
for(i=0;i<n;i++){
    a.insertdata();
    a.showdata();
}

For example the progrom shows this

1 John 5
1 John 5
2 Ron 6
2 Ron 6

I want the input and output to be separate and sorted by grade: Input:

1 John 5
2 Ron 6

Output:

2 Ron 6
1 John 5

For the sorting i'm using this

bool operator()(student const & a, student const & b) {
        return a.success < b.success;
    }

If someone can help I will be grateful Thanks in advance :)

2
  • And in what kind of container your Student are going ? Commented Dec 16, 2013 at 10:40
  • 1
    Can you please edit your question to include a simple but complete example? Also known as a SSCCE. Commented Dec 16, 2013 at 10:41

2 Answers 2

2

You can use a predicate to pass to std:sort. For example:

bool by_grade_decr(student const & a, student const & b) {
    return a.grade > b.grade;
}

#include <algorithm> // for std::sort
#include <vector>

int main()
{
  std::vector<student> students = ....;
  std::sort(students.begin(), students.end(), by_grade_decr);
}
Sign up to request clarification or add additional context in comments.

2 Comments

std::vector<student> students; std::sort(students.begin(), students.end(), by_grade); Says that students it's not a type
@user3104718 that doesn't make sense. You must have an error or a typo somewhere.
1

Use the STL. Vector for the storage and the sort algorithm.

int n,i;
cin>>n;
vector<Student> storage;
student a;
for(i=0;i<n;i++){
    a.insertdata();
    a.showdata();
    storage.push_back(a);
}

sort(storage.begin(), storage.end());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.