【STL-map的简单应用】借还书系统

#include<iostream>
#include<map>
#include<string>
using namespace std;
map<string,int> book;
class Book
{
private:
	static int number;//借出书数量
	static int all_price;//借出总价值
public:
	void show()
	{
		if(book.empty()) cout<<"\n当前没有任何借出的书"<<endl;
		else 
		{
			cout<<"\n当前图书借出量为  "<<number<<endl
				<<"输出借出的所有图书的名字和价格"<<endl;
			map<string,int>::iterator p=book.begin();
			for(p;p!=book.end();p++) cout<<p->first<<' '<<p->second<<endl;
			cout<<"当前图书借出总价值为  "<<all_price<<endl;
		}
	}
	void borrow()
	{
		cout<<"输入借出的书名和价格"<<endl;
		string name;int price;
		cin>>name>>price;
		book.insert(pair<string,int>(name,price));
		all_price+=price;
		number++;
	}
	void restore()
	{
		while(true)
		{
			cout<<"输入归还的书名"<<endl;
			string name;
			cin>>name;
			map<string,int>::iterator i=book.find(name);
			if(i==book.end())
			{
				cout<<"查无此书,检查书名是否正确"<<endl;
				continue;
			}
			else 
			{
				cout<<"书名:   "<<i->first<<"   归还成功"<<endl;
				number--;
				all_price-=i->second;
				book.erase(i);
				break;
			}
			
		}
	
	}
};
int Book::number=0;
int Book::all_price=0;
int main()
  {
	  Book test;
	  cout<<"借出几本书?"<<endl;
	  int t=0;
	  cin>>t;
	  while(t--){test.borrow();}
	  test.show();
	  cout<<"\n归还几本书?"<<endl;
	  cin>>t;
	  while(t--){test.restore();}
	  test.show();
}

运行结果:

借出几本书?
3
输入借出的书名和价格
三体 58
输入借出的书名和价格
细胞生命的礼赞 30
输入借出的书名和价格
百年孤独 20


当前图书借出量为  3
输出借出的所有图书的名字和价格
百年孤独 20
三体 58
细胞生命的礼赞 30
当前图书借出总价值为  108


归还几本书?
1
输入归还的书名
三体
书名:   三体   归还成功


当前图书借出量为  2
输出借出的所有图书的名字和价格
百年孤独 20
细胞生命的礼赞 30
当前图书借出总价值为  50
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/u011590573/article/details/80030713