改数组长度

//改变数组长度


#include <iostream>


using namespace std;

// #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



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

  

posted @ 2021-11-06 22:17  CrossPython  阅读(107)  评论(0编辑  收藏  举报