C++ 实现自己的标准库之静态数组array

学c++同学必会的一项技能必须懂得STL,STL真的非常的强大,因此自己想实现一个自己的STL库,因此在读了《STL源码剖析》之后,开始了编写自己的库道路。以下是一个普通数组容器的实现代码,并定义了迭代器。
.h文件

#pragma once
#ifndef MYSTL_ARRAY_H
#define MYSTL_ARRAY_H

#include<stddef.h>//ptrdiff_t 头文件
#include<stdexcept>//out_of_range

namespace mystl {
	template<typename T, size_t Num>
	class array {
	public:
		typedef T value_type;
		typedef value_type* pointer;
		typedef value_type& reference;
		typedef size_t  size_type;
		typedef ptrdiff_t difference;
	public:
		typedef value_type* iterator;
		typedef const value_type* const_iterator;
		array() {
			for (int i = 0; i < Num; i++) {
				_M_instance[i] = NULL;
			}
		}
		array(const array<T, Num>& a) {
			*this = a;
		}
		~array() {}
		iterator begin() { return iterator(&_M_instance[0]); }
		iterator end() { return iterator(&_M_instance[Num]); }

		const_iterator begin()const { return const_iterator(&_M_instance[0]); }
		const_iterator end()const { return const_iterator(&_M_instance[Num]); }

		reference front() { return _M_instance[0]; }
		reference back() { return _M_instance[Num - 1]; }

		pointer data() { return _M_instance; }//返回一个指向容器首个元素的指针。

		//将 val 这个值赋值给容器中的每个元素
		void fill(const value_type& val) {
			for (int i = 0; i < Num; i++) {
				_M_instance[i] = val;
			}
		}
		void swap(array<T, Num>& a) {
			array<T, Num> cur = a;
			a = *this;
			*this = cur;
		}
		reference at(size_type n) {
			if (n >= Num)
				throw std::out_of_range("out_of_range");
			return _M_instance[n];
		}
		reference operator [](size_type n) { return at(n); }
		void operator =(const array<T, Num>& a) {
			for (int i = 0; i < Num; i++) {
				_M_instance[i] = a._M_instance[i];
			}
		}
		size_type size() { return Num; }
		size_type max_size() { return size(); }
		bool empty() { return false; }

	private:
		value_type _M_instance[Num ? Num : 1];
	};
}

#endif

测试函数文件

#include<iostream>
#include"array.h"

using namespace std;
void print(const mystl::array<int, 10>& b) {
	for (mystl::array<int, 10>::const_iterator it = b.begin(); it != b.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
}

int main() {
	mystl::array<int, 10> a;//std命名空间中有array, 直接使用导致不确定
	for (int i = 0; i < 10; i++) {
		a[i] = i;
	}
	print(a);

	cout << a.front() << endl;
	cout << a.back() << endl;

	int* p = a.data();
	cout << *p << endl;

	mystl::array<int, 10> b;
	b.fill(1);
	print(b);

	a.swap(b);
	print(b);
	print(a);
	return 0;
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

li_ao527

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值