View Single Post
Old 07-10-2004, 04:44 PM   #2 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Here is a starter. It contains all the coding skills with pointers to solve your little riddle. Now, my CArray behaves more like a (weirdo) list/stack then like an array. So your first job is to make it behave like an array.

So here is what you need to do:
  • Overload the subscript operator []. Even better, overload the () operator, but that might be slightly too unconvenient yet. Try it with [] first. The code for overloading it could be quite simple to start with: return internalData[idx] ;
  • Overload the = (assignment) operator. We want to write something like: FloatArray[3] = 2.5 ;

Once again, I gave you this crappy code on purpose, only to demonstrate the basic coding skills. It contains all techniques you need to know for now. Good luck!
Code:
#include <iostream>

using namespace std;

template <typename T> class CArray
{
public:
	CArray( ) : m_intSize(1)
	{
		//Guarantee that the array has at least one spot vacant.
		internalData = new T[1];
	}
	~CArray()
	{
		delete[] internalData;
		internalData = 0;
	}

	T getData( unsigned int idx )
	{
		return internalData[idx];
	}
	void Push( T val )
	{
		ResizeOne();
		internalData[m_intSize-1] = val;
	}
private:
	void ResizeOne()
	{
		T* temp = new T[m_intSize+1];

		for(int i = 0; i < m_intSize; ++i)
			temp[i] = internalData[i];
		delete[] internalData;
		internalData = new T[m_intSize+1];
		for(int i = 0; i < m_intSize; ++i)
			internalData[i] = temp[i];
		
		delete[] temp;
		m_intSize++;
	}

private:
	T* internalData;
	int m_intSize;
};

struct SpecialStruct
{
	//Whatever.	
};

int main()
{
	CArray<float> FloatArray;
	FloatArray.Push(2.5);
	FloatArray.Push(5.0);
	FloatArray.Push(8.73f);

	for(int i = 3; i != 0 ; --i)
		cout<<FloatArray.getData(i)<<endl;

	//Works great too.
	SpecialStruct AS, BS, CS;
	CArray<SpecialStruct> SSArray;
	SSArray.Push(AS);
	SSArray.Push(BS);
	SSArray.Push(CS);

	return 0;
}
Now if you're clever you'll take all the time in the world and read (and activly participate with) my tutorial on operator overloading in the C++ tutorial section. You will get trained in pointer handling as well, and you will be trained to know what you are doing. After study, this task is going to be a piece of cake...
__________________
Valmont is offline   Reply With Quote