-3
我有兩個迭代器和一個列表對元素字符串和size_t 我想要做的是將我的student_id和成績添加到結果列表中。C++從兩個迭代器創建一個列表對
我有兩個迭代器和一個列表對元素字符串和size_t 我想要做的是將我的student_id和成績添加到結果列表中。C++從兩個迭代器創建一個列表對
經過您的解釋和添加一些東西,我認爲您的錯誤是使用std::string::compare
。我測試過下面的代碼(避免使用addRegister
因爲Transcript
沒有定義):
#include <iostream>
#include <list>
#include <algorithm>
typedef struct Records_r {
std::string name; // Name of the records
std::string student_id;
std::list<std::pair<std::string, size_t>> grades; // List of (course, grade) pairs
} Records;
typedef std::list<std::pair<std::string, size_t>>::const_iterator Personaliteraattori;
std::list<std::pair<std::string, size_t>> findCourseResults(const std::list<Records>& registry, const std::string& course) {
std::list<std::pair<std::string, size_t>> results;
for (std::list<Records>::const_iterator it = registry.begin(); it != registry.end(); ++it) {
for (Personaliteraattori itt = it->grades.begin(); itt != it->grades.end(); ++itt) {
if (itt->first.compare(course) == 0) {
results.push_back(std::make_pair(it->student_id, itt->second));
}
}
}
return results;
}
int main()
{
std::string s = "Record of student_123456";
std::string id = "123456";
std::list<std::pair<std::string, size_t>> grades;
grades.emplace_back("Math", 2);
grades.emplace_back("Basic Math", 4);
grades.emplace_back("Advanced Math", 5);
grades.emplace_back("Math 1", 3);
Records t;
t.name = s;
t.student_id = id;
t.grades = grades;
std::list<Records> reg;
reg.push_back(t);
t.name = "Record of student_34567";
t.student_id = "34567";
t.grades.clear();
t.grades.push_back(std::pair<std::string,size_t>("Math",1));
t.grades.push_back(std::pair<std::string,size_t>("Catalan",5));
t.grades.push_back(std::pair<std::string,size_t>("Basic Math",9));
reg.push_back(t);
for (auto& tr : reg) {
std::cout << "Name: " << tr.name << std::endl;
std::cout << "Student id: " << tr.student_id << std::endl;
std::cout << "Grades:" << std::endl;
std::for_each(tr.grades.begin(), tr.grades.end(), [](std::pair<std::string, size_t> e)
{
std::cout << e.first << " : " << e.second << std::endl;
});
}
while(true){
std::cout<<"Enter a lecture: ";
std::string lecture;
std::getline(std::cin, lecture);
std::list<std::pair<std::string, size_t>> results = findCourseResults(reg,lecture);
for (auto& tr: results)
{
std::cout<<"StudentId: "<<tr.first<<" grades: "<<tr.second<<std::endl;
}
}
return 0;
}
請注意我如何使用std::string::compare
功能。這段代碼產生所需的輸出:
Name: Record of student_123456
Student id: 123456
Grades:
Math : 2
Basic Math : 4
Advanced Math : 5
Math 1 : 3
Name: Record of student_34567
Student id: 34567
Grades:
Math : 1
Catalan : 5
Basic Math : 9
Enter a lecture: Math
StudentId: 123456 grades: 2
StudentId: 34567 grades: 1
Enter a lecture: Catalan
StudentId: 34567 grades: 5
嗯....你忘了問一個問題.. – WhiZTiM
我沒有看到在'findCourseResults'什麼奇怪的。你能不能展示整個程序,看你如何在你的'Records'結構體中填充std :: list> grades'? –
apalomer
'reg'沒有被定義,並且沒有使用findCourseResults函數。 請創建一個[最小,完整,可驗證的示例](https://stackoverflow.com/help/mcve)。 – apalomer