我的地图和循环问题在这里。基本上我的地图是:
typedef map <int,string> studentRecord;
studentRecord sRecord;
我把键和元素放在for循环中:
for(int i = 0; i < sizephys; i++){
phys.push_back(new physics());
cout << "\nPlease enter student name:"<<endl;
getline(cin , namephys);
cout << "Please enter student id:"<<endl;
cin >> idphys;
cin.ignore();
phys[i]->setNameId(namephys, idphys);
phys[i]->addCourse(course, mark);
sRecord[idphys] = namephys;
}
现在的问题是我想在循环结束后使用地图进行搜索,例如:
int recordSearch;
cout << "\nPlease enter ID key of student to search their record." <<endl;
cin >> recordSearch;
searchDatabase(sRecord,recordSearch);
if (recordSearch == idphys)
{
phys[i]->printCourseInfo();
}
由于phys [i]在循环之外,显然不会工作。有没有其他方法可以做到这一点?谢谢
void searchDatabase(studentRecord &sRecord, int recordSearch)
{
studentRecord::iterator studRecordIter;
studRecordIter = sRecord.find(recordSearch);
if(studRecordIter != sRecord.end())
cout<<"\nFound record for student " <<
recordSearch << " = "<<
studRecordIter->second<<endl;
else
cout<<"Sorry, record " << recordSearch <<
" is not in database"<<endl;
}
答案 0 :(得分:1)
为什么你首先使用矢量(或任何pys
)?
无论如何,替换这一行:
sRecord[idphys] = namephys;
与
sRecord[idphys] = phys[i];
和
typedef map <int,string> studentRecord;
与
typedef map <int, physic *> studentRecord;
应该做的伎俩。
(另请注意,您没有给出矢量类型,因此可能会有一些调整)