最近在我的c ++课程中,我们学习了指针和类。
我尝试制作一个class Student
的程序,我们会指出给每个学生一个名字和考试成绩。
输入名称和测试分数后,将对它们进行排序,然后按从高到低的顺序列出。
我相信我的所有语法都是正确的,但我仍然在学习。我遇到的问题是,我第一次使用我的类时,我得到一个未初始化的局部变量错误,有关如何解决此问题的任何帮助吗?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
class Student {
private:
double score;
string name;
public:
void setScore(double a) {
score = a;
}
double getScore() {
return score;
}
void setName(string b) {
name = b;
}
string getName() {
return name;
}
};
void sorting(Student*, int);
int main()
{
Student *students;
string name;
int score;
int *count;
count = new int;
cout << "How many students? ";
cin >> *count;
while (*count <= 0) {
cout << "ERROR: The number of students must be greater than 0.\n";
cin >> *count;
}
for (int i = 0; i < *count; i++) {
cout << "Please enter the students name: ";
cin >> name;
students[i].setName(name);
cout << "Please enter " << students[i].getName() << "'s score: ";
cin >> score;
while (score < 0) {
cout << "ERROR: Score must be a positive number.\n";
cin >> score;
}
students[i].setScore(score);
}
sorting(students, *count);
for (int i = 0; i < *count; i++) {
cout << students[i].getName() << ": " << students[i].getScore() << endl;
}
system("PAUSE");
return 0;
}
void sorting(Student *s, int size) {
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if (s[j].getScore() > s[(j + 1)].getScore()) {
int tmp = s[(j + 1)].getScore();
s[(j + 1)].setScore(s[j].getScore());
s[j].setScore(tmp);
string tmp1 = s[(j + 1)].getName();
s[(j + 1)].setName(s[j].getName());
s[j].setName(tmp1);
}
}
}
}
答案 0 :(得分:1)
首先,您的Student
课程可以简化为:
struct Student {
double score;
std::string name;
};
因为访问者什么都不做。我还添加了std::
前缀,因为using namespace std
is considered a bad practice。
现在,不是使用指针存储学生,而是包含vector
并使用:
std::cout << "How many students? ";
int count;
std::cin >> count;
std::vector<Student> students(count);
如果没有加法器,也可以简化加载程序:
for (auto& student : students) {
std::cout << "Please enter the students name: ";
std::cin >> student.name;
std::cout << "Please enter " << student.name << "'s score: ";
std::cin >> student.score;
while (score < 0) {
std::cout << "ERROR: Score must be a positive number.\n";
std::cin >> student.score;
}
}
实际上,一旦你拥有了它,你可以把它放在istream& operator>>(istream&, Student&)
中并将其缩小为:
std::copy_n(std::istream_iterator<Student>(std::cin), students.size(), students.begin());
现在不再需要临时变量了(即使你想使用它们,也应该在使用之前定义,因此在循环内部。)
最后一件事就是你的分拣程序。首先,如果您只是提供一个比较器,那么您可以使用std::sort
:
std::sort(
begin(students),
end(students),
[](Student const& a, Student const& b) { return b.score < a.score; }
);
如果您坚持自己编写排序例程,至少使用std::swap
。