65,210
社区成员
发帖
与我相关
我的任务
分享/背包类,由一个map记录武器名字和个数,vector记录武器属性;
#include <iostream>
#include <string>
#include <vector>
#include <map>
//#include "F:\msdosd\gs\head\key.h"
using namespace std;
//typedef vector<Key> mups;
//typedef map<string,int> mup;
template <typename T>
class Bag//背包类
{
public:
Bag(){ }
bool del_bag(T& res);
void add_bag(T res);
bool emptybag(){return _bao.empty();}
void display_bag(bool shop=true);
vector<T> _baosu;//武器属性;
map<string, int> _bao ;//武器名字和个数
};
template <typename T>
bool Bag<T> ::del_bag(T& res)
{
vector<T>::iterator itis;
itis= _baosu.begin();
map<string, int>::iterator it;
it=_bao.find(res.first);
if( (it != _bao.end()) && (it->second >1) )
{
it->second--;
return true;
}
if( (it != _bao.end()) && (it->second =1) )
{
for(; itis != _baosu.end(); itis++)
{
if( itis->first == res.first)
{
_baosu.erase(itis);
_bao.erase(it);
return true;
}
}
}
return false;
}
template <typename T>
void Bag<T>::add_bag(T res)
{
map<string, int>::iterator it=_bao.begin();
it=_bao.find(res.first);
if(it != _bao.end())
{
it->second++;
}
else
{
_bao.insert(make_pair(res.first, 1));
_baosu.push_back(res);
}
}
template <typename T>
void Bag<T>::display_bag(bool shop)
{
map<string, int>::iterator it=_bao.begin();
vector<T>::iterator itis=_baosu.begin();
if(shop)
{
for(; it != _bao.end(); ++it)
{
cout<<it->first<<"\t数量:"<<it->second;
for(itis=_baosu.begin(); itis != _baosu.end();itis++)
{
if(itis->first == it->first)
{
cout<<"\t攻:"<<itis->second<<"\t";
}
}
}
cout<<endl;
}
else
{
for(; it != _bao.end(); ++it)
{
cout<<it->first<<"\t数量:"<<it->second;
for(itis=_baosu.begin(); itis != _baosu.end();itis++)
{
if(itis->first == it->first)
{
cout<<"\t攻:"<<itis->second<<"\t钱:"<<(it->second)*(itis->money)<<"\t";
}
}
}
cout<<endl;
}
}
int main()
{
return 0;