Array class templates (49)

Source: Internet
Author: User

Before we learned the class template, let's look at the array class template today. The template parameter can be a numeric parameter (non-type parameter), as follows

The use of numeric template parameters is limited , such as: a> variables cannot be used as template parameters;b> floating-point numbers cannot be used as template parameters;c> class objects cannot be used as template parameters . The essence is that the template parameter is the unit that is processed during the compilation phase, so it must be accurate and unique at compile time.

Down we use the function template to implement an interview question: the most efficient way to find the value of 1+2+3+...+n.

#include  <iostream> #include  <string>using namespace std;template<  Typename t, int n >void func () {    t a[n] = {0} ;         for (int i=0; i<n; i++)      {        a[N] = i + 1;     }        for (int i=0; i<n; i++)      {        cout << a[i] <<  endl;    }}template< int n >class sum{public:     static const int VALUE = Sum<N-1>::VALUE + N;}; template< >class sum < 1 >{public:    static  const int value = 1;}; Int main () {    cout <<  "1+2+3+...+10 = "  <<  sum<10>::value << endl;    cout <<  "1+2+3+...+100  =  " << Sum<100>::VALUE << endl;         return 0;}

We implement the recursive definition by using a function template, and the recursive exit is completely special to 1 o'clock. Let's take a look at the compilation results.

We see that this feature has been implemented. Let's go back to the template for the array class


Array.h Source

#ifndef  _array_h_#define _array_h_template< typename t, int n >class  array{    t m_array[n];p ublic:    int length ();     bool set (Int index, t value);     bool get (int  index, t& value);    t& operator[]  (Int index);     T operator[]  (Int index)  const;    virtual  ~array ();}; Template< typename t, int n >int array<t, n>::length () {     return n;} Template< typename t, int n >bool array<t, n>::set (int  Index, t value) {    bool ret =  (0 <= index)   &&  (index < n);         iF ( ret )     {        m_array[index]  = value;    }        return ret;} Template< typename t, int n >bool array<t, n>::get (int  Index, t& value) {    bool ret =  (0 <= index)  &&  (index < n);         if ( ret  )     {        value = m_array[ Index];    }        return ret;} Template< typename t, int n >t& array<t, n>::operator[]   (Int index) {    return m_array[index];} Template< typename t, int n >t array<t,&nbsP n>::operator[]  (Int index)  const{    return m_array[index];} Template< typename t, int n >array<t, n>::~array () {     } #endif



Test.cpp Source

#include <iostream> #include <string> #include "Array.h" using namespace Std;int Main () {array<double, 5&G T        Ad    for (int i=0; i<ad.length (); i++) {Ad[i] = i * i;    } for (int i=0; i<ad.length (); i++) {cout << ad[i] << Endl; } return 0;}

Let's take a look at the compilation results

We see that the creation of the array class has been implemented correctly. Come down and we'll refine the Intarray class before writing.


HeapArray.h Source

#ifndef  _HEAPARRAY_H_#define _HEAPARRAY_H_template< typename T >class  heaparray{private:    int m_length;    t* m_pointer;         heaparray (Int len);     bool construct ( );p ublic:    static heaparray<t>* newinstance (int length);     int length ();     bool get (int index, t&  value);     bool set (Int index, t value);    t&  operator []  (Int index);    t operator []  (int  Index)  const;    heaparray<t>& self ();     ~ Heaparray ();}; Template< typename t >heaparray<t>::heaparray (Int len) {     m_length =&nbSp;len;} Template< typename t >bool heaparray<t>::construct () {    m _pointer = new t[m_length];        return m_ Pointer != null;} Template< typename t >heaparray<t>* heaparray<t>::newinstance (int  Length) {    heaparray<t>* ret = new heaparray<t> (length);         if ( ! ( Ret && ret->construct ())  )     {         delete ret;                 ret = 0;    }         return ret;} Template< typename t >int heaparray<t>::length () {     Return m_length;} TeMplate< typename t >bool heaparray<t>::get (int index, t&  Value) {    bool ret =  (0 <= index)  &&  (index  <= length ());         if ( ret )      {        value = m_pointer[index];     }        return ret;} Template< typename t >bool heaparray<t>::set (Int index, T value ) {    bool ret =  (0 <= index)  &&  (index  <= length ());         if ( ret )      {        m_pointer[index] = value;     }        Return ret;} template< typename t >t& heaparray<t>::operator []  (int  Index) {    return m_pointer[index];} template< typename t >t heaparray<t>::operator []  (Int index)  const{    return m_pointer[index];} Template< typename t >heaparray<t>& heaparray<t>::self () {     return *this;} Template< typename t >heaparray<t>::~heaparray () {    delete[]  m_pointer;} #endif


Test.cpp Source

#include  <iostream> #include  <string> #include   "HeapArray.h" Using namespace  std;int main () {    heaparray<int>* pai = heaparray<int >::newinstance (        if) ( pai != NULL )     {        heaparray<int>& ai  = pai->self ();                 for (Int i=0; i<ai.length ();  i++)          {            ai[i] = i +  1;        }                 for (Int i=0; i<ai.length ();  i++)          {            cout << ai[i]  << endl;        }    }         delete pai;        return  0;}

Let's compile and look at the results.

Let's try the char type again, print the 10 letters after a

The fact that we have seen it implemented correctly proves that the array class template We write is capable of implementing various data types. Through the study of the array class template, the summary is as follows:1, the template parameters can be numeric parameters, 2, the array template parameters must be uniquely determined during compilation; 3, the array class template is based on the numerical template parameters, 4, the array class template is a simple linear table data structure.


Welcome Everybody to learn C + + language together, can add me qq:243343083.

Array class templates (49)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.