思路:
本题最需要注意的一个问题是 迭代器删除时 会失效
规避方法
for (vector<int>::iterator i = vector.begin();i != vector.end();i++) // 这里报错
{
....
i = vector.erase(i);
....
}
代码:
#include<iostream>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<string>
#include<cassert>
#include<cctype>
#include<memory.h>
#include<cstdio>
#include<sstream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<cstdlib>
using namespace std;
class book
{
public:
string name; //书名
string author;
book(string a=0, string b=0) :name(a), author(b){}
};
vector<book> books; //图书馆
vector<book> shelf; //记录每次SHELVE命令前 归还的临时书
vector<book> out; //记录借出的书
bool operator<(book &a, book&b)
{
return a.author < b.author || (a.author == b.author&&a.name < b.name);
}
void readbook()// 读取书籍
{
string t;
while (getline(cin, t) && t != "END")
{
size_t l = t.find("\""), r = t.rfind("\""),R=t.find("by ")+3;
book b(t.substr(l + 1, r - l - 1), t.substr(R)); // b(书名,作者名)
books.push_back(b); //book类
}
sort(books.begin(), books.end());
}
void readorder()// 读取 处理命令
{
string t;
while (getline(cin, t) && t != "END")
{
size_t l = t.find("\""), r = t.rfind("\""), R = t.find(" ");
string name = t.substr(l + 1, r - l - 1); //提取作者名
string comd = t.substr(0, 6); //提取命令
if (comd == "BORROW") //借出
{
for (vector<book>::iterator it = books.begin();it != books.end();it++)
{
if (it->name == name)
{
out.push_back(*it);
it=books.erase(it);
break;
}
}
}
else if (comd == "RETURN") //归还
{
for (auto& t : out)
{
if (t.name == name)
{
shelf.push_back(t);
break;
}
}
}
else if (comd == "SHELVE") // !!!
{
sort(shelf.begin(), shelf.end());
for (vector<book>::iterator jt = shelf.begin(); jt != shelf.end();)
//!!! 不需要++ 因为每次erase临时书架的书籍时 iterator都会重置为下一个
{
vector<book>::iterator it = books.begin();
int f = 0;
for (it = books.begin(); it != books.end(); it++)
{
if (*jt < *it) //找到合适摆放位置的后一个位置
{
f = 1;
if (it == books.begin())
cout << "Put \"" << jt->name << "\" first" << endl;
else if (it - 1 >= books.begin())
cout << "Put \"" << jt->name << "\" after \"" << (it - 1)->name <<"\""<< endl;
books.insert(it, *jt);
jt=shelf.erase(jt);
break;
}
}
if (f==0) //此次要摆放的书籍 最大
{
if (books.empty()) //图书馆为空
cout << "Put \"" << jt->name << "\" first" << endl;
else
cout << "Put \"" << jt->name << "\" after \"" << (books.end() - 1)->name << "\"" << endl;
books.push_back(*jt);
jt=shelf.erase(jt);
}
}
cout << "END" << endl;
}
}
}
int main()
{
readbook(); // 读取书籍
readorder(); // 读取 处理命令
return 0;
}
这道题一直报错比如vector iterators incompatible iterator not incrementable、改了俩小时 查资料才搞定 大佬勿喷 还是太菜 需要继续努力