当数组作为函数的参数按值传递时,它会隐式转换为指向其第一个元素的指针。声明数组的参数也调整为指针。
例如这些函数声明
void printarray( int array[100] );
void printarray( int array[10] );
void printarray( int array[] );
声明同一个函数,等价于
void printarray( int *array );
所以你还需要将数组的大小传递给函数,例如
void printarray( const int array[]. size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
std::cout << a[i] << std::endl;
}
}
您可以专门为通过引用传递的数组编写模板函数,例如
template <size_t N>
void printarray( const int ( &array )[N] )
{
for ( int x : array)
{
std::cout << x << std::endl;
}
}
或
template <typename T, size_t N>
void printarray( const T ( &array )[N] )
{
for ( auto x : array)
{
std::cout << x << std::endl;
}
}
但是与之前的函数相比,它有一个缺点,因为不同大小的数组是不同的类型,编译器会从模板中生成尽可能多的函数,就像你要与函数一起使用的不同类型的数组一样。
您可以使用标准算法,例如std::copy 或std::for_each 来输出一个数组。
例如
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
int array[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::copy( std::begin( array ), std::end( array ),
std::ostream_iterator<int>( std::cout, "\n" ) );
return 0;
}
另一种方法是使用标准类std::array,该类具有适当的成员函数begin 和end,基于范围的for 语句使用这些函数。例如
#include <iostream>
#include <array>
const size_t N = 10;
void printarray( const std::array<int, N> &array )
{
for ( int x : array ) std::cout << x << std::endl;
}
int main()
{
std::array<int, N> array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
printarray( array );
return 0;
}
但在这种情况下,如果您要输出具有不同数量或类型元素的 std::array 类的对象,您还需要编写一个模板函数。
例如
#include <iostream>
#include <array>
template <typename T, size_t N>
void printarray( const std::array<T, N> &array )
{
for ( auto x : array ) std::cout << x << std::endl;
}
int main()
{
std::array<int, 10> array1 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
printarray( array1 );
std::array<char, 10> array2 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
printarray( array2 );
return 0;
}