我有vector
的structs
。 我需要根据struct
中向量中的学生姓氏的字母顺序对向量进行排序。这可能吗?在struct
每个学生有下列信息:在其他函数中对结构体和向量部分的向量排序?
struct Student
{
string lastName;
string firstName;
string stdNumber;
double assgn1;//doubles are what I want to add in another function.
double assign2;
double assign3;
double assign4;
double midTerm;
double finalGrade;
bool operator<(Student const &other) const {
return lastName < other.lastName;
}
};
这是我students
矢量由填充:
int getFileInfo()
{
int failed=0;
ifstream fin;
string fileName;
vector<Student> students;// A place to store the list of students
Student s; // A place to store data of one student
cout<<"Please enter the filename of the student grades (ex. filename_1.txt)."<<endl;
do{
if(failed>=1)
cout<<"Please enter a correct filename."<<endl;
cin>>fileName;
fin.open(fileName.c_str());// Open the file
failed++;
}while(!fin.good());
while (fin >> s.firstName >> s.lastName >> s.stdNumber){
cout<<"Reading "<<s.firstName<<" "<<s.lastName<<" "<<s.stdNumber<<endl;
students.push_back(s);
}
vector<Student>::iterator loop = students.begin();
vector<Student>::iterator end = students.end();
fin.close();
return 0;
}
所以我想在最后的名字struct
排序,然后是能够在另一个函数中处理矢量中的每个“Student”
结构体。这可能吗?
我想能够将double
零件添加到我在另一个函数中的矢量中的每个学生。然后我希望能够打印出每个学生的所有信息。如果我在students
矢量所在的功能中打印出每个学生的信息,但我需要使用另一个功能void gradeInput()
进行打印。我将cin>>
每double
年级为每个学生,一次一个学生。我在想它会看起来像这样:
void gradeInput()
{
For(each student)// I don’t know what to do to in this for loop to loop through
//each student. I want to make it so everywhere “stud” is change to the
//next student after one loop iteration.
//I made a default `Student` called ‘stud’ to show this example..
cout<<"Student "<<stud.firstName<<" "<<stud.lastName<<" "<<stud.stdNumber<<":";
cout<<"Please, enter a grade (between 0.0 and 100.0) for ... "<<endl;
cout<<"Assignment 1:";
cin>>stud.assgn1;
cout<<endl;
cout<<"Assignment 2:";
cin>>stud.assign2;
cout<<endl;
cout<<"Assignment 3:";
cin>>stud.assign3;
cout<<endl;
cout<<"Assignment 4: ";
cin>>stud.assign4;
cout<<endl;
cout<<"MidTerm: ";
cin>>stud.midTerm;
cout<<endl;
cout<<"Final Exam: ";
cin>>stud.finalGrade;
cout<<endl;
return;
}
希望这是有道理的,我可以得到一些帮助!我的老师对我没有帮助,因为她没有回复电子邮件,并有45分钟的办公时间,所以你所有友好的人都是一个伟大的资产!谢谢!
P.S.对不起,糟糕的代码格式,我仍然试图找出网站的代码输入。
上课还剩下一个月,我们还没有学过D班:...所以请帮助我。我是否使用'class'而不是'struct'?我看到你评论了课程的开始,我知道我必须初始化并创建一些东西,但我不知道是什么。你能在那里写一些伪代码,看看我能弄清楚该怎么做?与'&operator'功能一样,以前从未使用过。谢谢 - – b3orion
不 - 您可以将其保留为结构体。只需在该结构中定义你的'operator <'。 –
请参阅http://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c –