为什么这段代码:
void printarray(int array[]) {
for (int x: array) {
std::cout << x << std::endl;
}
}
生成此编译时错误?
error: 'begin' was not declared in this scope
for (int x: array) {
基于范围的for
循环我有什么问题?
答案 0 :(得分:13)
您的问题是array
实际上不是数组。当你写
void printarray(int array[])
与
相同void printarray(int* array)
由于在没有附加大小参数的情况下无法确定指针指向的元素数量,因此无法将其与基于范围的for循环一起使用。
您需要做的是通过引用传递数组,以便数组不会衰减成指针。如果你知道数组的确切大小,那么你可以使用
void printarray(int (&array)[size_you_want_here])
如果你想让函数更通用,那么它可以使用不同大小的数组,那么你可以使用像
这样的模板template<std::size_t N>
void printarray(int (&array)[N])
在上述两种情况下,您现在都有一个实际数组而不是指针,因此您可以将它与基于范围的for循环一起使用。
另请注意,我们可以使用
使该功能完全通用template<typename T, std::size_t N>
void printarray(T (&array)[N]) {
for (auto&& x : array) {
std::cout << x << "\n";
}
}
您还会注意到我将std::endl
更改为"\n"
。通常,您不希望使用endl
,因为它在流上显式调用flush()
。通常"\n"
就是您所需要的,如果输出仍未刷新,那么您可以自己调用flush()
。
答案 1 :(得分:5)
当数组作为函数的参数传递时,它会隐式转换为指向其第一个元素的指针。声明数组的参数也会调整为指针。
所以例如这些函数声明
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
,它具有适用于基于for语句的范围的成员函数begin
和end
。例如
#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;
}
答案 2 :(得分:1)
printarray接收的参数实际上是一个int *,范围不知道在哪里停止。在这种情况下,您需要将长度作为参数发送,并为
执行常规操作