题解 | #查找学生信息#
查找学生信息
https://www.nowcoder.com/practice/fe8bff0750c8448081759f3ee0d86bb4
#include <iostream> #include <map> using namespace std; struct student{ string name; string sex; int age; student():name("无名氏"),sex("男"),age(0){} // 需要一个空参数的构造器,因为[]操作符没找到键时会初始化一个空值,需要调用空参构造 student(string str,string c,int a):name(str),sex(c),age(a){} }; int main(){ int n,m; while (cin>>n) { map<string,student> stuMap; string key,str,c; int a; for (int i = 0; i < n; ++i) { cin>>key>>str>>c>>a; stuMap.insert(pair<string,student>(key,student(str,c,a))); // 不能用=号赋值,将struct通过=赋值需要重载=号 } cin>>m; for (int i = 0; i < m; ++i) { cin>>key; if (stuMap.find(key)!=stuMap.end()){ cout<<key<<" "<<stuMap[key].name<<" "<<stuMap[key].sex<<" "<<stuMap[key].age<<endl; } else{ cout<<"No Answer!"<<endl; } } } return 0; }