问题
I want a template class to contain two template dynamic arrays as member variables. I use also a member function to assign to them values. However I got problem with the code and I do not know the reason (probably the syntax). What is the problem in the following code?
template<typename T>
class ArrayHolder
{
public:
ArrayHolder();
void setArrays( T [], T [],int,int);
private:
T *array1;
T *array2;
};
template<typename T>
ArrayHolderHolder<T>::setArrays(T firstarray[],T secondarray[] ,int N1, int N2)
{
array1 = new T[N1];
array2 = new T[N2];
}
After the initialization of the dynamic arrays in setArrays, what is the most effective to copy the arrays from the parameters (firstarray,secondarray) to them?
回答1:
ArrayHolderHolder<T>::setArrays(T firstarray[],T secondarray[] ,int N1, int N2)
^^^^^^^^^^^^^^^^^
Here is one typo. The class name is ArrayHolder, notArrayHolderHolder. Also, you didn't write the return type.
Since you cannot pass array (by value), it is better if you use pointer notation function in parameter list, and since it is class template, prefer defining the functions in the class itself:
template<typename T>
class ArrayHolder
{
public:
ArrayHolder();
void setArrays(T *firstarray,T *secondarray ,int N1, int N2)
{
array1 = new T[N1];
array2 = new T[N2];
//if you want to copy, then use `std::copy` as:
std::copy(firstarray, firstarray + N1, array1);
std::copy(secondarray, secondarray + N2, array2);
}
private:
T *array1;
T *array2;
};
By the way, instead of raw arrays, you could use st::vector as:
std::vector<T> array1;
std::vector<T> array2;
And same in the parameter list of setArrays as well. If you do so, then setArray would become this:
void setArrays(const std::vector<T> & first, const std::vector<T> & second)
{
//maybe you need to do this!
array1.clear();
array2.clear();
array1.insert(array1.end(), first.begin(), first.end());
array2.insert(array2.end(), second.begin(), second.end());
}
Simple, isn't it? No memory allocation, no deallocation!
Or even better, if you accept the arguments by value, then you could write this:
void setArrays(std::vector<T> first, std::vector<T> second)
{
//no need to clear!
array1.swap(first);
array2.swap(second);
}
The last implementation is an idiomatic solution, preferred by library implementers.
回答2:
In addition to @Nawaz answer: you forgot void return type before setArrays() definition.
回答3:
std::copy is the most effective way. http://www.cplusplus.com/reference/algorithm/copy/
std::copy(firstarray, firstarray + N1, array1);
std::copy(secondarray, secondarray + N2, array2);
Of course, this is only if you insist on using arrays. Personally I always use a container from the standard template library. In this case I would use a std::vector but to each their own.
来源:https://stackoverflow.com/questions/8366505/dynamic-template-arrays