基于静态数组的容器类bag实现

来源:互联网 发布:先导爱知同人吧 编辑:程序博客网 时间:2024/05/18 14:24

头文件bag1.h:

#ifndef MAIN_WTF_H
#define MAIN_WTF_H
#include  <cstdlib>


namespace main_wtf_1
{
class bag
{
public:
typedef int value_type;
typedef std::size_t size_type;
static const size_type CAPACITY = 30;


bag() { used = 0; }


size_type erase(const value_type& target);
bool erase_one(const value_type& target);
void insert(const value_type& entry);
void operator +=(const bag& addend);


size_type size() const { return used; };
size_type count(const value_type& target) const;
value_type getData(size_type i)  const { return data[i]; };



private:
value_type data[CAPACITY];
size_type used;


};
bag operator +(const bag& b1,const bag& b2);
}


#endif


实现文件bag1.cpp:

#include <algorithm>
#include<iostream>
#include <cassert>
#include "bag1.h"
using namespace std;


namespace main_wtf_1
{
// const bag::size_type bag::CAPACITY;


bag::size_type bag::erase(const value_type& target)
{
size_type num = 0;


while(erase_one(target))
{
num++;


}
return num;

}


bool bag::erase_one(const value_type& target)
{
for(std::size_t i=0;i<used;i++)
{
if(target == data[i])
{
data[i] = data[used-1];
data[used-1] = 0;
used--;
return true;
}
}
return false;
}


void bag::insert(const value_type& entry)
{
if(this->size() >= bag::CAPACITY)
{
cout<<"No room for new entry!"<<endl;
return;
}
else
{
data[used++] = entry;
}
}


bag::size_type bag::count(const value_type& target) const
{
size_type num = 0;
for(size_t i=0;i<used;i++)
{
if(target == data[i])
num++;
}
return num;
}


void bag::operator+=(const bag& addend)
{
if((this->size()+addend.size()) > bag::CAPACITY)
{
cout<<"No room for new entry!"<<endl;
return;
}
else
{
for(size_t i=0;i<addend.size();i++)
{
data[used++] = addend.getData(i);


}
}
}


bag operator +(const bag& b1,const bag& b2)
{
bag bag1;
if((b1.size()+b2.size()) > bag::CAPACITY)
{
cout<<"No room for new entry!"<<endl;
return bag1;
}
else
{
bag1 += b1;
bag1 += b2; 


return bag1;
}
}


}

测试代码:

#include <iostream>
#include <cstdlib>
#include "bag1.h"
using namespace std;
using namespace main_wtf_1;


void get_ages(bag& bags);
void check_ages(bag& ages);


int main()
{
bag ages;
bag ages2;




get_ages(ages);
get_ages(ages2);
ages+=ages2;


check_ages(ages);
cout<<"May your family live happy!"<<endl;


return EXIT_SUCCESS;




}


void get_ages(bag& ages)
{
int user_input;


cout<<"Type the ages in your family"<<endl;
cout<<"Type a nagative number when you are done:"<<endl;
cin>>user_input;
while(user_input >= 0)
{
if(ages.size()<ages.CAPACITY)
ages.insert(user_input);
else
cout<<"I have run out of room can't add that age."<<endl;
cin>>user_input;
}
}


void check_ages(bag& ages)
{
int user_input;
cout<<"Type those ages again,Press return after each age: "<<endl;
while(ages.size()>0)
{
cin>>user_input;
if(ages.erase_one(user_input))
cout<<"Yes, I've got that age and will remove it."<<endl;
else
cout<<"No,that age does not occur!"<<endl;
}
}



0 0
原创粉丝点击