I am currently following Deitel's C How to Program 9th edition textbook and am having difficulties with a particular problem.
The problem is to take a the code written earlier on in the chapter using the vector class template and rewrite using the array class template.
In the code there are the following functions for inputting data into the vector and displaying the vector.
// output vector contents
void outputVector( const vector< int > &array )
{
for ( int item : array )
cout << item << " ";
cout << endl;
} // end function outputVector
// input vector contents
void inputVector( vector< int > &array )
{
for ( int &item : array )
cin >> item;
} // end function inputVector
My confusion here is I do not know how to create such functions which take an array template as an argument, for example with lengths 7 and 10 as is the case in the vector template version of the code.
Is this possible or must a function be defined for a specific length array template?
Further, if this is the case, then what really is the value of using an array over a vector?
Thanks
CodePudding user response:
You can try the following
template<std::size_t S>
void inputVector(std::array<int, S>& arr)
{
//do your thing
}
CodePudding user response:
If I understand your question, you could use a template to allow different length arrays, so modifying your vector versions would look like
template <std::size_t N>
void outputArray(const std::array<int, N>& data)
{
for (int item : data)
std::cout << item << " ";
std::cout << std::endl;
}
template <std::size_t N>
void inputArray(std::array<int, N>& data)
{
for (int &item : data)
std::cin >> item;
}
Then you can call this with whatever sized arrays
int main()
{
std::array<int, 3> a = {1,2,3};
std::array<int, 5> b = {1,2,3,4,5};
outputArray(a);
outputArray(b);
}