自定义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;
}
还没有评论,来说两句吧...