第三章 容器类
首先,用VS2010出现LINK ERROR: fatal error LNK1123: failure during conversion to COFF:
解决办法为:
然后,写了一个容器类:bag,该类是可以存储一个整数集合的容器。
bag.h
#include "stdafx.h"
#include <iostream>
using namespace std;
class bag
{
public:
bag();
~bag(){};
void insert(int a);
int size();
int count(int b);
bool erease_one(int target); // erase target only once
int erease(int target);
void print();
bag operator +(bag& added);
void test();
private:
int* data;
int used;
int capacity;
};
bag::bag()
{
capacity = 20;
data = new int[capacity];
used = 0;
}
void bag::insert(int a)
{
if(used>capacity-1)
{
capacity *= 2;
int* datacopy = new int[capacity];
for(int j = 0; j < capacity; j++)
datacopy[j] = data[j];
delete data;
data = datacopy;
}
data[used++] = a;
}
int bag::size()
{
return used;
}
int bag::count(int b)
{
int result = 0;
for(int i = 0; i < used; i++)
{
if(data[i] == b)
{
result++;
}
}
return result;
}
bool bag::erease_one(int target)
{
for(int i = 0; i<used; i++)
{
if(data[i] == target)
{
for(int j = i; j < used; j++)
data[j] = data[j+1];
used--;
return true;
}
}
return false;
}
int bag::erease(int target)
{
int result = 0;
while(erease_one(target))
{
result++;
}
return result;
}
bag bag::operator +(bag &added)
{
if(used+added.size() < capacity)
{
for(int i = 0; i < added.size(); i++)
{
data[used+i] = added.data[i];
}
used = used+ added.size();
}
return *this;
}
void bag::print()
{
for(int i = 0; i < used; i++)
cout << data[i]<<" ";
cout<<endl;
}
void bag::test()
{
bag a,b;
a = bag();
b = bag();
for(int i = 0; i < 10; i++)
{
a.insert(i%3);
b.insert(i+10);
}
a.print();
cout << "the size of the bag is " << a.size()<<endl;
int target = 2;
cout <<"the number ----- " << target<< "------ appears " << a.count(target)<<" times!!"<<endl;
cout << "the target -- " <<target<<"-- appears " << int(a.erease(target))<<" times!!!"<<endl;
a.print();
cout << "add bag a and b: " << endl;
a = a + b;
a.print();
}
bag.cpp
#include "stdafx.h"
#include <iostream>
#include "bag.h";
using namespace std;
int main()
{
bag a;
a.test();
system("pause");
return 0;
}