[英]Vectors of Pointers passed into different functions
我正在尝试使用 new 运算符来创建对象。 我在调整代码以管理指向我创建的对象的新指针时遇到了一些麻烦。
这是我的代码:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
struct StudentRecord {
public:
StudentRecord(
string id,
string firstName,
string lastName,
int age,
string phoneNumber,
double gpa
) {
Id = id;
FirstName = firstName;
LastName = lastName;
PhoneNumber = phoneNumber;
Age = age;
Gpa = gpa;
}
void display() {
cout << " Student ID: " << Id << endl;
cout << " First Name: " << FirstName << endl;
cout << " Last Name: " << LastName << endl;
cout << " Phone Number: " << PhoneNumber << endl;
cout << " Age: " << Age << endl;
cout << " GPA: " << Gpa << endl;
cout << endl;
}
string Id;
string FirstName;
string LastName;
string PhoneNumber;
int Age;
double Gpa;
};
void displayStudents(vector<StudentRecord>& students) {
for (auto student : students) {
student.display();
}
}
int main()
{
ifstream inputFile;
inputFile.open("TestFile.csv");
string line = "";
vector<StudentRecord> students;
while (getline(inputFile, line)) {
stringstream inputString(line);
//StudentId, Last Name, FirstName, Age, Phone Number, GPA
string studentId;
string lastName;
string firstName;
int age;
string phone;
double gpa;
string tempString;
getline(inputString, studentId, ',');
getline(inputString, lastName, ',');
getline(inputString, firstName, ',');
getline(inputString, tempString, ',');
age = atoi(tempString.c_str());
getline(inputString, phone, ',');
getline(inputString, tempString);
gpa = atof(tempString.c_str());
students.push_back(new StudentRecord(studentId, lastName,firstName, age, phone, gpa));
line = "";
}
displayStudents(students);
}
具体来说这里有一个问题:
students.push_back(new StudentRecord(studentId, lastName,firstName, age, phone, gpa));
我知道我需要调整displayStudents
函数以接收指向对象的指针向量,但我不确定如何执行此操作。
students
是vector<StudentRecord>
类型,因此,您不需要调用new
。
如果您想练习new
,建议将其更改为vector<StudentRecord*>
。 请注意,建议使用托管指针类型(例如unique_ptr
、 smart_ptr
)而不是“裸”指针。
如果您只是想让代码正常工作,请使用:
students.emplace_back(studentId, lastName,firstName, age, phone, gpa));
在任何一种情况下,您都可以在仅在此处使用的本地生成的字符串上考虑std::move()
,即std::move(studentId), std::move(lastName), ...
在emplace_back()
的参数中emplace_back()
或push_back()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.