新的c ++ 11 for循环原因:"错误:'begin'未在此范围内声明"

时间:2015-03-04 12:01:52

标签: c++ c++11

我正在尝试学习c ++,所以我编写了一个使用新的c ++ 11 for循环的短程序,这使编译器给我一个我不理解的错误。 这是我的c ++代码:

#include <iostream>
#include <cmath>
using namespace std;

float legge_oraria_moto_accelerato(float a[3]){
    return a[2]*a[0] + 0.5*a[1]*a[0]*a[0];
}
int corri(float (f)(float array[3]), float arrays[3][3])
    { for(auto i:arrays) cout << f(i) << '\n';
    return 0;
} 

int main()
{ 
return 0;
}

这是编译器的(g ++ -std = gnu ++ 11)错误:

mezzo.cpp: In function ‘int corri(float (*)(float*), float (*)[3])’:
mezzo.cpp:9:18: error: ‘begin’ was not declared in this scope
     { for(auto i:arrays) cout << f(i) << '\n';
                  ^
mezzo.cpp:9:18: note: suggested alternatives:
In file included from /usr/include/c++/4.9/bits/basic_string.h:42:0,
                 from /usr/include/c++/4.9/string:52,
                 from /usr/include/c++/4.9/bits/locale_classes.h:40,
                 from /usr/include/c++/4.9/bits/ios_base.h:41,
                 from /usr/include/c++/4.9/ios:42,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from mezzo.cpp:1:
/usr/include/c++/4.9/initializer_list:89:5: note:   ‘std::begin’
     begin(initializer_list<_Tp> __ils) noexcept
     ^
/usr/include/c++/4.9/initializer_list:89:5: note:   ‘std::begin’
mezzo.cpp:9:18: error: ‘end’ was not declared in this scope
     { for(auto i:arrays) cout << f(i) << '\n';
                  ^
mezzo.cpp:9:18: note: suggested alternatives:
In file included from /usr/include/c++/4.9/bits/basic_string.h:42:0,
                 from /usr/include/c++/4.9/string:52,
                 from /usr/include/c++/4.9/bits/locale_classes.h:40,
                 from /usr/include/c++/4.9/bits/ios_base.h:41,
                 from /usr/include/c++/4.9/ios:42,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from mezzo.cpp:1:
/usr/include/c++/4.9/initializer_list:99:5: note:   ‘std::end’
     end(initializer_list<_Tp> __ils) noexcept
     ^
/usr/include/c++/4.9/initializer_list:99:5: note:   ‘std::end’

1 个答案:

答案 0 :(得分:21)

基于范围的for循环适用于数组,但不适用于指针。这里的问题是arrays实际上是指针而不是数组。

如果有一个声明为数组的函数参数,则将其调整为指针类型。您可以在此处使用参数float arrays[3][3]看到此信息:在编译器错误消息中,您可以看到实际参数类型是指向数组float (*)[3]的指针,该数组不能与基于范围的数组一起使用for loop。

如果您通过引用传递数组(float (&arrays)[3][3]),它将不会以这种方式调整为指针,因此将使用基于范围的for循环。