【问题标题】:Trying to sort Vector of Objects尝试对对象向量进行排序
【发布时间】:2018-03-25 05:35:08
【问题描述】:

正如标题所示,我正在尝试按 GPA 对对象向量进行排序。我的主要问题是放置一个方法来定义我的比较函数。向量本身包含五个字段的对象,包括:字符串名称、字符串 ssn、字符串年份、浮动信用、浮动 gpa。我知道他们有一种使用排序运算符的方法。我是 C++ 新手,所以我对这种语言不是很了解。感谢您的帮助!代码如下:

    #include <iostream>
    #include <string>
    #include <iterator>
    #include <iomanip>
    #include <fstream>
    #include <vector>
    #include <sstream>
    #include <algorithm>
    #include <cstdlib>
    #include <list>


    using namespace std;

    class Student {

    //declare local variables
    protected:
     string name;   //people with names longer than 21 characters will just 
                    have to make do
     string ssn;     // Social Secturity Number. 
     float gpa;     //Most up to date gpa for the student
     float credits; //Number of student's credit hours

                //build public methods
      public:

    //Default Constructor
     Student() {}


//Student constructor. Besides the character arrays, everything else is passed by reference.
Student(const string n, const string s, string sGPA, string sCredits) {
    name = n;
    ssn = s;
    gpa = (float)atof(sGPA.c_str());
    credits = (float)atof(sCredits.c_str());
}
string getName() {
    return name;
}
string getSSN() {
    return ssn;
}
float getGPA() {
    return gpa;
}
float getCredit() {
    return credits;
}
//a function that is expected to be implemented and overridden by subclasses
virtual void print() const {

    cout << '\n' << endl;
    cout << "Student's name: " << name << endl;
    cout << "Student SSN: " << ssn << endl;
    cout << "Student's current GPA: " << gpa << endl;
    cout << "Student's credit hours: " << credits << endl;
}


// a pure virtual function for implementation later. Makes whole class Abstract
virtual float tuition() const = 0;


   };


class Undergrad : public Student {

    //declare local variables

protected:
    float undergrad_rate = 380.0;
    string year;


    //build public methods

public:

    //Default Constructor
    Undergrad() {}


    //Undergrad Constructor
    Undergrad(const string n, const string s, string uGPA, string uCredits, string y) :
        Student(n, s, uGPA, uCredits), year(y) {}


    //Display the contents of undergrad
    void print() const {
        Student::print();
        cout << "Undergrad Rate: " << undergrad_rate << endl;
        cout << "Year: " << year << endl;
    }


    //Display undergrad's current year
    string get_year() {
        return year;
    }


    //Display the undergrad's current rate
    float get_rate() {
        return undergrad_rate;
    }


    //Set a undergrad's current year
    void set_year(string y) {
        year = y;
    }


    //Display the cost for an undergrad to attend university
    float tuition() const {
        return 1000000;
    }

};



int main() {
    ifstream ip("data.txt");

    if (!ip.is_open()) std::cout << "ERROR: File not found" << '/n';
    string name;
    string ssn;
    string year;
    string credit;
    string gpa;
    list<Undergrad> myList;


    list<Undergrad>::iterator i;
    //Undergrad g(name, ssn, year, credit, gpa);
    while (ip.good()) {
        getline(ip, name, ',');
        getline(ip, ssn, ',');
        getline(ip, gpa, ',');
        getline(ip, credit, ',');
        getline(ip, year, '\n');

        //  float number = stoi(gpa);
        //float number1 = stoi(credit);
        Undergrad g(name, ssn, year, credit, gpa);
        myList.push_back(g);







    }
    ip.close();
    //This deletes the last object in the list and stores it in a temp object. It assigns that object to the beginning of the list.
    Undergrad temp = myList.back();
    myList.pop_back();
    myList.insert(myList.begin(), temp);



    /*  for (int i = 0; i < myList.size(); i++) {
            cout << "Name: " << myList[i].getName() << endl;
            cout << "SSN: " << myList[i].getSSN() << endl;
            cout << "Year: " << file[i].get_year() << endl;
            cout << "Credit:  " << file[i].getCredit() << endl;
            cout << "GPA " << file[i].getGPA() << endl;
            cout << " " << endl;


        }

    */
    /*for (Undergrad &x : myList) { //Goes through my list and displays its contents
        x.print(); //This isn't bringing up errors.

    }
    */
    //This code copy the contents of the list to a vector.
    std::vector<Undergrad> vect{ std::make_move_iterator(std::begin(myList)),
        std::make_move_iterator(std::end(myList)) };



    std::sort(vect.begin(), vect.end(), CompareGPA);

    for (Undergrad &x : vect) {
        x.print();
    }

    system("pause");
    return 0;
}

此外,这是我试图实现比较的代码

        bool CompareGPA(const Student& left, const Student& right) {
        return left.gpa > right.gpa;
        }

【问题讨论】:

  • 有效吗?你到底有什么问题?
  • 问题是我不知道把那个方法放在哪里。外面主要它说GPA是不可访问的。我切换到 return left.getGPA() > right.getGPA() 并引发另一个错误。
  • 你有没有想过使用const
  • @HenryReichard 你的“另一个错误”是什么?
  • 那是很多代码。很多不相关的代码。请减少到minimal reproducible example。您最终可能会在此过程中自己发现问题。

标签: c++ sorting object vector


【解决方案1】:

使用 lambda 可以这样实现:使用属性 int get_gpa() const 访问受保护的成员。

std::sort(vect.begin(), vect.end(), [] (const Student& left, const Student& right)
  {
     return left.get_gpa() > right.get_gpa();
   });

这里如何实现属性(返回受保护变量的成员函数):

   int get_gpa() const
   {
     return gpa;
    }

【讨论】:

  • 它说 gpa 无法访问
  • 会员受到保护,所以您不能
  • 即使我删除了受保护的情况仍然如此
  • @HenryReichard:使用属性访问受保护的成员变量。
  • @HenryReichard 当您删除受保护的类时默认为私有访问,因此更改受公共保护或使用 getGPA 函数。
猜你喜欢
  • 1970-01-01
  • 2020-02-22
  • 2014-04-08
  • 2011-03-23
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
相关资源
最近更新 更多