I have two iterators and a list with pair elements string and size_t What i am trying to do is add my student_id and grade into the result list.
After your explanations and adding some stuff I think your error is in the use of std::string::compare
. I've tested the following code (avoiding the use of addRegister
because Transcript
is not defined):
#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;
}
Please, note how I use the std::string::compare
function. This code produces the desired output:
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