前田稔(Maeda Minoru)の超初心者のプログラム入門
/*★ Main Program Step2 前田 稔 ★*/ #include <iostream> #include "Vector.h" using namespace std; void main() { int i; Vector<int> v; // 逆順に格納する for(i=9; i>=0; i--) v.push_back(i); // 表示 cout << "v "; for(i=0; i<v.size(); i++) cout << v.at(i) << " "; cout << endl; // 添え字で参照する cout << "v[0]=" << v[0] << " v[4]=" << v[4] << " v[9]=" << v[9] << endl; cout << "キャパシティー= " << v.capacity() << " サイズ= " << v.size() << endl; } |
/*★ Vector Class Step2 前田 稔 ★*/ //※ 省略されている部分は前回作成した Vector Class を参照して下さい { public: typedef T* iterator; typedef T& reference; iterator begin() { return array; } iterator end() { return array+current_size; } int size() { return current_size; } int capacity() { return array_size; } // at関数はoperator[]と異なり、チェックつき reference at(int index) { if( size() <= index ) { cerr << "error" << endl; exit(1); } return array[index]; } void push_back(const T &x); private: void resize(int size); iterator array; int current_size; int array_size; }; |
template<class T> void Vector<T>::push_back(const T &x) { if(current_size >= array_size) resize( size() + 10 ); array[current_size+1] = array[current_size]; array[current_size] = x; current_size++; } |
// 配列の大きさをcurrent_size+1に変える template<class T> void Vector<T>::resize(int size) { iterator tmp = new T[size+1]; iterator tmp2 = tmp; iterator itr = begin(); for(; itr!=end(); itr++,tmp++) *tmp = *itr; delete [] array; array = tmp2; array_size = size; } #endif |