自定义STL容器(Base on array)

carray.h

#ifndef _CARRAY_H_
#define _CARRAY_H_

#include <cstddef>

template <class T, std::size_t thesize>
class carray {
private:
	T v[thesize];

public:
	typedef T				value_type;
	typedef T*				iterator;
	typedef const T*		const_iterator;
	typedef T&				reference;
	typedef const T&		const_reference;
	typedef std::size_t		size_type;
	typedef std::ptrdiff_t	difference_type;

	// iterator support
	iterator begin() { return v; }
	const_iterator begin()const { return v; }
	iterator end() { return v + thesize; }
	const_iterator end()const { return v + thesize; }

	// direct element access
	reference operator[](std::size_t i) { return v[i]; }
	const_reference operator[](std::size_t i)const { reutrn v[i]; }

	// size is constant
	size_type size()const { return thesize; }
	size_type max_size()const { return thesize; }

	// conversion to ordinary array
	T* as_array() { return v; }
};



#endif

测试 main.cpp

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <string>
#include <ctime>
#include <functional>
#include <algorithm>
#include <sstream>
#include "carray.h"
using namespace std;

int main()
{
	carray<int, 10> a;

	for (size_t i = 0; i < a.size(); ++i) {
		a[i] = i + 1;
	}

	copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
	cout << endl;

	reverse(a.begin(), a.end());
	copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
	cout << endl;

	transform(a.begin(), a.end(),
		a.begin(),
		negate<int>());
	copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
	cout << endl;

	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值