基于范围的for-loop on数组传递到非主函数 [英] Range based for-loop on array passed to non-main function

查看:184
本文介绍了基于范围的for-loop on数组传递到非主函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在gcc 4.8.2中编译以下代码时,会出现以下错误:

When I try to compile the following code in gcc 4.8.2, I get the following error:


test.cc: In function ‘void foo(int*)’:
test.cc:15:16: error: no matching function for call to ‘begin(int*&)’
   for (int i : bar) {
                ^


与来自模板库中更深层次的其他人一起。

Along with a while bunch of others from deeper in the template library.

#include <iostream>
using namespace std;

void foo(int*);

int main() {
  int bar[3] = {1,2,3};
  for (int i : bar) {
    cout << i << endl;
  }
  foo(bar);
}

void foo(int* bar) {
  for (int i : bar) {
    cout << i << endl;
  }
}



如果我重新定义 foo 使用索引for循环,然后代码按预期编译和运行。此外,如果我将基于范围的输出循环移动到 main ,我也得到预期的行为。

If I redefine foo to use an indexed for loop, then the code compiles and behaves as expected. Also, if I move the range-based output loop into main, I get the expected behaviour as well.

如何将数组 bar 传递到 foo 以这样的方式,它能够执行基于范围的for循环?

How do I pass the array bar to foo in such a way that it is capable of executing a range-based for-loop on it?

推荐答案

=http://stackoverflow.com/q/1461432/1938163>数组衰减成一个指针,你失去了一个重要的信息:它的大小。

With the array decaying into a pointer you're losing one important piece of information: its size.

使用数组引用,您的基于范围的循环可以工作:

With an array reference your range based loop works:

void foo(int (&bar)[3]);

int main() {
  int bar[3] = {1,2,3};
  for (int i : bar) {
    cout << i << endl;
  }
  foo(bar);
}

void foo(int (&bar)[3]) {
  for (int i : bar) {
    cout << i << endl;
  }
}

函数签名中的数组大小),

or, in a generic fashion (i.e. without specifying the array size in the function signature),

template <std::size_t array_size>
void foo(int (&bar)[array_size]) {
  for (int i : bar) {
    cout << i << endl;
  }
}

尝试

这篇关于基于范围的for-loop on数组传递到非主函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆