c – 基于函数循环的范围,它将数组作为值传递

前端之家收集整理的这篇文章主要介绍了c – 基于函数循环的范围,它将数组作为值传递前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Range based for-loop on array passed to non-main function2个
这些天我自己学习C并且我有一些问题需要理解为什么这段代码不使用#g -std = c 11 source.cpp进行编译.实际上我使用哪个特定标准并不重要,它只是不编译.
#include <iostream>
#include <string>
using namespace std;
int print_a(char array[])
{
    for(char c : array)
        cout << c;
    cout << endl;
    return 0;
}
int main(void)
{
    char hello[] {"Hello!"};
    print_a(hello);
    return 0;
}

错误消息:

debian@debian:~/Documents$g++ -std=c++11 source.cpp
source.cpp: In function ‘int print_a(char*)’:
source.cpp:6:15: error: ‘begin’ was not declared in this scope
  for(char c : array)
               ^
source.cpp:6:15: 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 source.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’
source.cpp:6:15: error: ‘end’ was not declared in this scope
  for(char c : array)
               ^
source.cpp:6:15: note: suggested alternatives:
In file included from /usr/include/c++/4.9/bits/basic_string.h:42:0,from source.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’

解决方法

它不编译的原因是在C中,一个函数参数如char array []被调整为char * array.你的功能真的很像
int print_a(char* array)
{
 ....
}

并且基于范围的循环不能处理指针.

一种解决方案是通过引用传递数组. C不允许您按值传递普通数组.例如,这将接受5个字符的数组:

int print_a(const char (& array)[5])
{
   for(char c : array) cout << c;
   cout << endl;
   return 42;
}

为了将其推广到不同大小的数组,您可以使用模板:

template <std::size_t N>
int print_a(const char (& array)[N])
{
   for(char c : array) cout << c;
   cout << endl;
   return 42;
}

当然,有更简单的方法来打印以null结尾的字符串:

char hello[] {"Hello!"};
cout << hello << endl;

并且有标准库类型可以使传递字符串或char缓冲区对象更容易.例如,std :: string,std :: vector< char&gt ;,std :: array< char,N> (其中N是编译时常量.)

猜你在找的C&C++相关文章