c/c + + template and STL small sample series self built Array

Keywords: C++

c/c + + template and STL small example series < 1 > self bui lt Array

The self built Array provides the following external interfaces

Method Function description
Array() The nonparametric construction method constructs an array with the number of elements as template parameters
Array(int length) There is a parameter construction method, and the number of construction elements is an array of parameter length
~Array() Destructor
int size() Returns the number of elements in an array
T& get(int num) Returns a reference to an element in an array with a specified subscript
void set(T data, int num) Sets the value of the specified subscript element
T& operator [] (int num) Overloaded [] function of type T

The following code uses the private element size1, which was originally intended to be named by size, but because the int size() method is declared in the public method, it can't be compiled, so it's strange to call size1.

my_array.h

ifndef __my_array__
#define __my_array__
template<typename T, int n>
class Array {
public:
  Array();
  Array(int length);
  ~Array();
  T& get(int idx);
  T& operator[](int idx);
  void set(T data, int idx);
  int size();
private:
  T* pt;
  int size1;

};
//Constructor
template<typename T, int n>
Array<T, n>::Array(){
  pt = new T[n];
  size1 = n;
}
//Constructor
template<typename T, int n>
Array<T, n>::Array(int length){
  pt = new T[length];
  size1 = length;
}
//Destructor
template<typename T, int n>
Array<T, n>::~Array(){
  delete [] pt;
}
//Get the number of array elements
template<typename T, int n>
int Array<T,n>::size(){
  return size1;
}
//Gets the element with the specified subscript
template<typename T, int n>
T& Array<T, n>::get(int num){
  if(num >= size1 || num < 0){
    //abnormal                                                      
  }
  else{
    return pt[num];
  }
}
//Sets the value of the specified subscript element
template<typename T, int n>
void Array<T, n>::set(T data, int num){
  if(num >= size1 || num < 0){
    //abnormal                                                      
  }
  else{
    pt[num] = data;
  }
}
//Overloaded [] function of element type
template<typename T, int n>
T& Array<T, n>::operator[](int num){
  if(num >= size1 || num < 0){
    //abnormal                                                      
  }
  else{
    return *(pt + num);
  }
}
#endif

Test procedure:

#include <iostream>
#include <string>
#include "my_array.h"

using namespace std;

int main(){
  Array<int, 5> ary;
  for(int i = 0; i < ary.size(); ++i){
    ary.set(i * 10, i);
    cout << ary.get(i) << " ";
    cout << ary[i] << ", ";
  }
  cout << endl;

  Array<string, 3> asr(4);
  for(int i = 0; i < asr.size(); ++i){
    asr.set("AAA", i);
    cout << asr.get(i) << " ";
    cout << asr[i] << ", ";
  }
  cout << endl;
  return 0;
}

Posted by gaogier on Wed, 01 Jan 2020 21:42:18 -0800