用STL里的map很简单
要注意的几点:
1.key的分离,网上查到一种比较好的方法
char *point=book[i].keyWord;//关键词分离
while(*point){
sscanf(point,"%s",str);
point+=strlen(str)+1;
string stemp(str);
mm_keyWord[stemp].push_back(i);
}
这里sscanf和scanf用法差不多,只不过以字符串作为输入
int sscanf ( const char * s, const char * format, ...);
2.cout的格式:
因为id不足七位的前面要补零,之前一直用的是
printf("%05d")
查了一下cout格式化的方法
ostream::fmtflags old;//old保存格式
old = cout.flags();//保存原格式
cout.width(7);//设置新格式,宽度为7
cout.fill('0');//宽度不足用'0'补齐
cout << Publish[search][i] << endl;//按新格式输出
cout.flags(old);//返回老格式
#include<iostream>
#include<map>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
map<string, vector<int>>Title, Author, Key, Publish,Year;
int main(){
freopen("1.in", "r", stdin);
int n;
cin >> n;
int id,i;
string title, author, key, publish,year;
for (i = 0; i < n; i++){
cin >> id;
cin.get();
getline(cin, title);
Title[title].push_back(id);
getline(cin, author);
Author[author].push_back(id);
char ch = '\0';
while (ch!= '\n'){
cin >> key;
Key[key].push_back(id);
cin.get(ch);
}
getline(cin, publish);
Publish[publish].push_back(id);
cin >> year;
Year[year].push_back(id);
}
int times;
cin >> times;
ostream::fmtflags old;
while (times--){
int num;
cin >> num;
cin.get();
cin.get();
string search;
getline(cin, search);
switch (num){
case 1:{
sort(Title[search].begin(), Title[search].end());
cout << num << ": " << search << endl;
if (!Title[search].size())
cout << "Not Found" << endl;
for (i = 0; i < Title[search].size(); i++){
old = cout.flags();
cout.width(7);
cout.fill('0');
cout << Title[search][i] << endl;
cout.flags(old);
}
}break;
case 2:{
sort(Author[search].begin(), Author[search].end());
cout << num << ": " << search << endl;
if (!Author[search].size())
cout << "Not Found" << endl;
for (i = 0; i < Author[search].size(); i++){
old = cout.flags();
cout.width(7);
cout.fill('0');
cout << Author[search][i] << endl;
cout.flags(old);
}
}break;
case 3:{
sort(Key[search].begin(), Key[search].end());
cout << num << ": " << search << endl;
if (!Key[search].size())
cout << "Not Found" << endl;
for (i = 0; i < Key[search].size(); i++){
if (i&&Key[search][i] == Key[search][i - 1])
continue;
old = cout.flags();
cout.width(7);
cout.fill('0');
cout << Key[search][i] << endl;
cout.flags(old);
}
}break;
case 4:{
sort(Publish[search].begin(), Publish[search].end());
cout << num << ": " << search << endl;
if (!Publish[search].size())
cout << "Not Found" << endl;
for (i = 0; i < Publish[search].size(); i++){
old = cout.flags();
cout.width(7);
cout.fill('0');
cout << Publish[search][i] << endl;
cout.flags(old);
}
}break;
case 5:{
sort(Year[search].begin(), Year[search].end());
cout << num << ": " << search<<endl;
if (!Year[search].size())
cout << "Not Found" << endl;
for (i = 0; i < Year[search].size(); i++){
old = cout.flags();
cout.width(7);
cout.fill('0');
cout << Year[search][i] << endl;
cout.flags(old);
}
}
}
}
return 0;
}