之前未解决的一道题,这次按自己的思路一点点写出来的~
#include <iostream>
#include <string>
#include <vector>
#include <set>
using namespace std;
const int maxn = 10001;
struct bookInfo{
string id, year, title, author, publisher;
vector<string> keywords;
}book[maxn];
//getKeywords函数实现功能将读入的一行多个关键字分离成多个string类,push进bool[index]的keywords容器内
void getKeywords(int index, string str){ //传参index为book[]数组的下标,str为输入的一行所有关键字
string word;
int len = (int)str.size();
for(int i = 0; i < len; i++){
if(str[i] != ' '){
word += str[i];
}else{
book[index].keywords.push_back(word);
word.clear();
}
}
book[index].keywords.push_back(word);
}
int main(){
int n;
scanf("%d%*c", &n); //注意要接收下一个换行符
for(int i = 0; i < n; i++){
string temp;
getline(cin, book[i].id); //用getline读入一整行,如果上一行有整型、char型等输入,记得getchar()接收换行符
getline(cin, book[i].title);
getline(cin, book[i].author);
getline(cin, temp);
getKeywords(i, temp);
getline(cin, book[i].publisher);
getline(cin, book[i].year);
}
int m;
cin >> m;
getchar(); //接收换行符
for(int j = 0; j < m; j++){
string query;
getline(cin, query);
cout << query << endl;
int num = query[0] - '0';
query.erase(0, 3);
set<string> ans;
switch(num){
case 1:
for(int i = 0; i < n; i++){
if(book[i].title == query){
ans.insert(book[i].id);
}
}
break;
case 2:
for(int i = 0; i < n; i++){
if(book[i].author == query){
ans.insert(book[i].id);
}
}
break;
case 3:
for(int i = 0; i < n; i++){
int k = (int)book[i].keywords.size();
for(int j = 0; j < k; j++){
if(book[i].keywords[j] == query){
ans.insert(book[i].id);
}
}
}
break;
case 4:
for(int i = 0; i < n; i++){
if(book[i].publisher == query){
ans.insert(book[i].id);
}
}
break;
case 5:
for(int i = 0; i < n; i++){
if(book[i].year == query){
ans.insert(book[i].id);
}
}
break;
}
int len = (int)ans.size();
if(len == 0){
cout << "Not Found" << endl;
}else{ //set容器只能用迭代器访问,不能用下标访问
for(set<string>::iterator it = ans.begin(); it != ans.end(); it++){
cout << *it << endl;
}
}
}
return 0;
}