C++を使ってみる

速度の要る部分だけでもC/C++で書けないかと思い、CもそこそこにC++を試してみた。
とりあえずテンプレートを使ってArrayクラスを作ってみた。
ソースコード貼る。

#include <iostream>

using namespace std;

template <class X> class Array {
  X *_data;
  int _size;
  int _max;

public:
  Array(int max=2) {
    _max = max;
    _size = 0;
    _data = new X[max];
  }

  ~Array() {
    delete [] _data;
  }

  X get (int i) {
    return _data[i];
  }

  X &operator [] (int i) {
    return _data[i];
  }

  void expand() {
    _max *= 2;
    X *new_data = new X[_max];
    
    for (int i=0; i<_size; i++) {
      new_data[i] = get(i);
    }
    delete [] _data;
    _data = new_data;
  }

  Array<X> &operator << (X item) {
    push(item);
    return *this;
  }

  void push(X item) {
    if (_size >= _max) {
      cout << "expands: " << _max;
      expand();
      cout << " to " << _max << endl;
    }
    _data[_size ++] = item;
    cout << "pushed " << item << endl;
  }

  X pop() {
    return _data[-- _size];
  }

  bool empty() {
    return _size == 0;
  }

  int size() {
    return _size;
  }
};

template <class TYPE>
ostream &operator << (ostream &stream, Array<TYPE> &ary) {
  for (int i=0; i<ary.size(); i++) {
    stream << ary[i];
  }
  return stream;
}

int main() {
  cout << "= test #1" << endl;

  Array<int> ary;

  for (int x=1; x <= 3; x++) {
    ary.push(x);
  }

  while (not ary.empty()) {
    cout << "popped " << ary.pop() << endl;
  }

  cout << "= test #2" << endl;
  Array<char *> ary2(3);

  ary2 << "a" << "b" << "c";

  cout << "ary2[0] = \"A\"" << endl;
  ary2[0] = "A";

  cout << "cout << ary2 << endl; \n#=> " << ary2 << endl;

  ary2 << "d";
  cout << "cout << ary2[3] << endl; \n#=> " << ary2[3] << endl;

  return 0;
}

当方の環境だと"gcc file && ./a.out"とやるとiostream関係でコンパイルエラーになってしまったので、"c++ file && ./a.out"で実行した。

% c++ array.cpp && ./a.out
= test #1
pushed 1
pushed 2
expands: 2 to 4
pushed 3
popped 3
popped 2
popped 1
= test #2
pushed a
pushed b
pushed c
ary2[0] = "A"
cout << ary2 << endl;
#=> Abc
expands: 3 to 6
pushed d
cout << ary2[3] << endl;
#=> d

#翌日気づいたが、vectorクラスで同じことができた!