我有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 –