代码之家  ›  专栏  ›  技术社区  ›  Karma

如何找到存储在c++vector中的对象的类方法?

  •  0
  • Karma  · 技术社区  · 8 年前

    我是C++noob,如果这是一个简单的问题,请原谅,我从过去几天就一直在尝试解决这个问题。

    有一个名为student的类,它存储学生的姓名、年龄和分数。每个学生的个人资料(年龄、姓名和分数存储在一个班级中)。有 n 一个班级的学生因此 vector<student*> 创建,它存储指向类中所有学生配置文件的指针。

    我想打印存储在矢量中的值。如果有任何提示,我将不胜感激!

    #include <cstdlib>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <iterator>
    #include <string>
    using namespace std;
    
    class student{
    private:
        string name;
        float marks;
        int age;
    public:
        student(): name("Null"), marks(0),age(0){}
        student(string n, float m,int a): name(n), marks(m),age(a){}
        void set_name();
        void set_marks();
        void set_age();
        void get_name();
        void get_marks();
        void get_age();
    };
    void student::set_name(){
    cout<<"Enter the name: ";
    cin >> name;
    }
    void student::set_age(){
    cout << "Enter the age: ";
    cin >> age;
    }
    void student::set_marks(){
    cout<<"Enter the marks ";
    cin>> marks;
    }
    void student::get_name(){
        cout<<"Name: "<< name<<endl;
    }
    void student::get_age(){
        cout<<"Age: "<< age<<endl;
    }
    
    void student::get_marks(){
        cout<<"Marks: "<< marks<<endl;
    }
    
    
    int main() {
        int n;
        cout<<"Enter the number of students: ";
        cin >> n;
        vector <student*> library_stnd(n);
        for(int i=0;i<n;i++){
            student* temp = new student;
            temp->set_name();
            temp->set_age();
            temp->set_marks();
            library_stnd.push_back(temp);
    
        }
    
    
        for (auto ep: library_stnd){
             ep->get_age();
        }
        return(0);
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Petar Petrovic    8 年前

    vector <student*> library_stnd(n) 创建大小的向量 n . 然后在第一个for循环中 library_stnd.push_back(temp) temp 到library\u stnd的末尾,并且不首先更改 n 项目。

    问题是第一个 n 中的项目 library_stnd 初始化为零[1],在第二个for循环中取消引用它是一种未定义的行为。[2]

    我的建议是使用以下任一方法:

    1. vector <student*> library_stnd library\u stnd。推回(温度)
    2. 向量(<学生*>library\u stnd(n) library_stnd[i] = temp

    另一个建议

    1. vector<student> 而不是 vector<*student> 然后 for (auto& ep: library_stnd)
    2. '\n' 而不是 endl [3]
    3. double 而不是 float [4]

    [1] - What is the default constructor for C++ pointer?

    [2] - C++ standard: dereferencing NULL pointer to get a reference?

    [3] - C++: "std::endl" vs "\n"

    [4] - https://softwareengineering.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double