自定义STL容器(Base on array)

喜欢ヅ旅行 2022-08-20 02:19 82阅读 0赞

carray.h

  1. #ifndef _CARRAY_H_
  2. #define _CARRAY_H_
  3. #include <cstddef>
  4. template <class T, std::size_t thesize>
  5. class carray {
  6. private:
  7. T v[thesize];
  8. public:
  9. typedef T value_type;
  10. typedef T* iterator;
  11. typedef const T* const_iterator;
  12. typedef T& reference;
  13. typedef const T& const_reference;
  14. typedef std::size_t size_type;
  15. typedef std::ptrdiff_t difference_type;
  16. // iterator support
  17. iterator begin() { return v; }
  18. const_iterator begin()const { return v; }
  19. iterator end() { return v + thesize; }
  20. const_iterator end()const { return v + thesize; }
  21. // direct element access
  22. reference operator[](std::size_t i) { return v[i]; }
  23. const_reference operator[](std::size_t i)const { reutrn v[i]; }
  24. // size is constant
  25. size_type size()const { return thesize; }
  26. size_type max_size()const { return thesize; }
  27. // conversion to ordinary array
  28. T* as_array() { return v; }
  29. };
  30. #endif

测试 main.cpp

  1. #include <iostream>
  2. #include <vector>
  3. #include <deque>
  4. #include <list>
  5. #include <string>
  6. #include <ctime>
  7. #include <functional>
  8. #include <algorithm>
  9. #include <sstream>
  10. #include "carray.h"
  11. using namespace std;
  12. int main()
  13. {
  14. carray<int, 10> a;
  15. for (size_t i = 0; i < a.size(); ++i) {
  16. a[i] = i + 1;
  17. }
  18. copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
  19. cout << endl;
  20. reverse(a.begin(), a.end());
  21. copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
  22. cout << endl;
  23. transform(a.begin(), a.end(),
  24. a.begin(),
  25. negate<int>());
  26. copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
  27. cout << endl;
  28. system("pause");
  29. return 0;
  30. }

发表评论

表情:
评论列表 (有 0 条评论,82人围观)

还没有评论,来说两句吧...

相关阅读