学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;
}