zoukankan      html  css  js  c++  java
  • 117.类模板封装数组类

     1 #include <iostream>
     2 #include <initializer_list>
     3 #include <memory>
     4 using namespace std;
     5 
     6 template <class T,int n>
     7 class myarray
     8 {
     9 private:
    10     T * p;
    11 public:
    12     myarray(initializer_list<T> mylist)
    13     {
    14         //开辟内存
    15         p = new T[n];
    16         //内存清零
    17         memset(p, 0, sizeof(T)*n);
    18         int length = mylist.size();
    19         if (length > n)
    20         {
    21             abort();
    22         }
    23         else
    24         {
    25             int i = 0;
    26             //数据填充
    27             for (auto j : mylist)
    28             {
    29                 p[i] = j;
    30                 i++;
    31             }
    32         }
    33     }
    34     void show()
    35     {
    36         for (int i = 0; i < n; i++)
    37         {
    38             cout << p[i] << endl;
    39         }
    40     }
    41 
    42     //模板排序
    43     void sort()
    44     {
    45         for (int i = 0; i < n - 1; i++)
    46         {
    47             for (int j = 0; j < n - 1 - i; j++)
    48             {
    49                 if (p[j] < p[j + 1])
    50                 {
    51                     T temp = p[j]; 
    52                     p[j] = p[j + 1];
    53                     p[j + 1] = temp;
    54                 }
    55             }
    56         }
    57     }
    58 
    59     myarray()
    60     {
    61         delete[]p;
    62     }
    63 };
    64 
    65 void main()
    66 {
    67     myarray<int, 10> my1 = { 1,2,3,4,5,6,7,8,9 };
    68     my1.sort();
    69     my1.show();
    70     cin.get();
    71 }
  • 相关阅读:
    【心情】codeforces涨分啦!
    redis
    rabbitmq
    lucene
    MongoDB
    负载均衡
    分布式存储
    Memcache
    websocket
    Remoting
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8613674.html
Copyright © 2011-2022 走看看