C++改變數組長度
代碼
//改變數組長度 #ifndef CHANGELENGTH1D_H #define CHANGELENGTH1D_H #include<stdexcept> #include<algorithm> template<typename T> void changeLength1D(T *&a,int oldLength, int newLength) { if(newLength < 0) throw std::runtime_error("New length must be >=0"); T* temp = new T[newLength]; int number = std::min(oldLength, newLength); //copy( from_vector.begin(), from_vector.end(), to_vector.begin()) std::copy(a, a+number, temp); delete [] a; a = temp; } #endif // CHANGELENGTH1D_H
驗證頭文件
#include <iostream> #include "changelength1d.h" using namespace std; int main() { try{ double* a = new double[2]; a[0] = 11; a[1] = 12; changeLength1D(a,2,6); for(int i=2;i<6;i++) a[i]=i; for(int i=0;i<6;i++) cout << a[i] << endl; return 0; }catch(runtime_error err) { cout << err.what() << endl; } }
參考文獻
shihoumacilihtml