c++ - 传递给非主函数的数组上基于范围的for循环

标签 c++ gcc c++11 for-loop

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

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

以及来自模板库更深处的其他一些。

#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 中,我也会得到预期的行为。

如何将数组 bar 传递给 foo,使其能够在其上执行基于范围的 for 循环?

最佳答案

随着array decaying变成一个指针,你会丢失一条重要的信息:它的大小。

有了数组引用,你的基于范围的循环就可以工作了:

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;
  }
}

或者,以通用方式(即不在函数签名中指定数组大小)

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

Try it out

关于c++ - 传递给非主函数的数组上基于范围的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26182907/

相关文章:

c++ - 模板类不继承基模板类

c++ - 空结构元素的 OpenCV 腐 eclipse /膨胀错误输出?

c - GCC 不保存/恢复函数调用的保留寄存器

c++ - 标准是否要求流构造函数不访问流缓冲区?

c++ - 生命周期延长和条件运算符

c++ - 意外的输出

c++ - fwrite 在 C++ 中的工作

c - 如何在 Linux 中从 C 打印毫秒和纳秒精度的时间差?

c - linux 上的段错误-在 windows 上工作

c++ - 消息分配运算符不使用交换