sort

Use student class. 

#ifndef STUDENT_HPP_INCLUDED
#define STUDENT_HPP_INCLUDED

using namespace std;

class student{
private:
    int NO;
    int Grade;
    string Name;

public:
    student():NO(0),Grade(0),Name(""){}
    student(int NO_, int Grade_, string Name_):NO(NO_),Grade(Grade_),Name(Name_){}
    student(const student& s){
        this->setNO(s.getNO());
        this->setGrade(s.getGrade());
        this->setName(s.getName());
    }

    int getNO() const { return NO; }
    int getGrade() const { return Grade; }
    string getName() const { return Name; }
    void setNO(int NO_) { NO = NO_; }
    void setGrade(int Grade_) { Grade = Grade_; }
    void setName(string Name_) { Name = Name_; }

    bool operator==(const student& s) const {
        return this->getNO() == s.getNO();
    }
    bool operator<(const student& s) const {
        return this->getGrade() < s.getGrade();
    }
    bool operator>(const student& s) const {
        return this->getGrade() > s.getGrade();
    }

    void print(){
        cout << NO << "\t" << Name << "\t" << Grade << endl;
    }
};

#endif // STUDENT_HPP_INCLUDED

1. sort students according to their grades, from lowest to highest;

2. find first top 2 students;

#include <vector>
#include <functional>
#include <iostream>
#include <algorithm>
#include <./student.hpp>

using namespace std;

int main(){
    vector<student> sv;
    student s1(1001, 70, "Sam");
    student s2(1002, 85, "Tim");
    student s3(1003, 90, "James");
    student s4(1004, 50, "David");
    sv.push_back(s1);
    sv.push_back(s2);
    sv.push_back(s3);
    sv.push_back(s4);

    cout << "Original Students Vector: " << endl;
    auto itr = sv.begin();
    while(itr!=sv.end()){
        itr->print();
        itr++;
    }

    // sort by grade, from low to high
    sort(sv.begin(), sv.end(), less<student>());
    cout << "After sort(): " << endl;
    itr = sv.begin();
    while(itr!=sv.end()){
        itr->print();
        itr++;
    }

    // find first two highest grade
    vector<student> first2(2);
    partial_sort_copy(sv.begin(), sv.end(), first2.begin(), first2.end(), greater<student>());
    cout << "First 2 top students: " << endl;
    auto itr2 = first2.begin();
    while (itr2!=first2.end()){
        itr2->print();
        itr2++;
    }

    return 0;
}
results are


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值