数据结构与面向对象学习1

第三章 容器类


首先,用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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值