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

标签 c++ algorithm object stl

我是 C++ 菜鸟,如果这是一个简单的问题,请原谅我,过去几天我一直在努力解决这个问题。

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

我想打印存储在 `vector 中的值 我真的很感激任何提示!

#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);
}

最佳答案

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

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

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

  1. vector <student*> library_stndlibrary_stnd.push_back(temp)
  2. vector <student*> library_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

关于c++ - 如何找到存储在 C++ vector 中的对象的类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47828667/

相关文章:

javascript - JS - 将对象转换为数组

C# 在查找类型后使用对象属性

C++ 随机数

python - 返回三个相同连续字母的最小移动次数

c++ - 使用现有项目进行 CppUnit 测试

javascript - 奇数的完美平方

algorithm - 后缀树中的后缀链接是否与 aho-corasick 自动机中的失败边相同?

JavaScript : How to check if particular key is exist or not

c++ - 在 Linux 中读取文件的最快方法?

c++ - boost::posix_time::ptime 到 UTC8601?