C++改变数组长度

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;
    }
}

参考文献

shihoumacili

posted @ 2018-06-05 20:20  静世孔明  阅读(5446)  评论(0编辑  收藏  举报