[ create a new paste ] login | about

Link: http://codepad.org/OzQ8dSlo    [ raw code | output | fork ]

C++, pasted on Feb 8:
//
// JavaScript みたいな配列に今一歩
// 

template<typename V>
class TVar {
public:
	V val; 
	TVar(): val(0) {}
	TVar(V v): val(v) {}
	TVar(const TVar &var) { val = var.val; }
	bool operator==(const V &v) { return val == v; }
	TVar& operator=(V v) { val = v; return *this; }
	V& operator=(TVar &var) { return var.val; }
};

template<class T>
class TArray {
	TVar<T> *ptr;
	
	void copy(const TArray &ar)
	{
		ptr = ar.ptr;
		length = ar.length;
		const_cast<TArray*>(&ar)->ptr = NULL; // コピコン対策
	}
public:
	int length;		// 書き換え出来てしまうのが格好悪いが

	~TArray() { if(ptr) delete [] ptr; }

	TArray(): ptr(0) {}
	TArray(int i)
	{
		ptr = new TVar<T>[i];
		memset(ptr, 0, i*sizeof(T));
		length = i;
	}
	
	TArray(const TArray &ar) { copy(ar); }
	TArray& operator=(const TArray &ar) { copy(ar); return *this; }
	
	TVar<T>& operator[](int i)
	{
		if(i < length) return ptr[i];
		
		TVar<T> *tmp = new TVar<T>[i+1];
		memset(tmp, 0, (i+1) * sizeof(TVar<T>*));

		if(length)
		{
			memcpy(tmp, ptr, length * sizeof(TVar<T>*));
			delete [] ptr;
		}
		
		length = i+1;
		ptr = tmp;
		return ptr[i];
	}
};

typedef TArray<int> Array;

// ---------------------------------------------------------

int main()
{
	Array ar = Array(10);

	for(int i=0;i<ar.length; ++i)
	{
		ar[i] = i;
		if(ar[i] == 5) printf("5! ... ");
		printf("%d\n", ar[i].val);
	}
	
	ar[20] = 100;
	printf("%d\n", ar[20].val);
	
	return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
0
1
2
3
4
5! ... 5
6
7
8
9
100


Create a new paste based on this one


Comments: