基于范围的for-loop on数组传递给非主函数

cas*_*avo 9 c++ gcc for-loop c++11

当我尝试在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) {
                ^
Run Code Online (Sandbox Code Playgroud)

与模板库中更深层次的其他一些人一起.

#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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

如何barfoo一种能够在其上执行基于范围的for循环的方式传递数组?

Mar*_* A. 16

随着数组衰减成指针,你丢失了一条重要的信息:它的大小.

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

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Try it out


Che*_*Alf 5

对于固定大小的数组,您可以

  • 通过引用传递原始数组。

  • 通过引用传递std::array

  • 通过引用传递std::vector

自然的选择(对于固定大小的数组)是std::array,即

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

void foo(array<int, 3> const& bar) {
  for (int i : bar) {
    cout << i << endl;
  }
}

int main() {
  array<int,3> const bar = {1,2,3};
  for (int i : bar) {
    cout << i << endl;
  }
  foo(bar);
}
Run Code Online (Sandbox Code Playgroud)