首页  >  文章  >  后端开发  >  如何在 C 中使用基于范围的 For 循环并将数组传递给非主函数?

如何在 C 中使用基于范围的 For 循环并将数组传递给非主函数?

Barbara Streisand
Barbara Streisand原创
2024-10-25 03:01:30119浏览

How to Use Range-Based For-Loops with Arrays Passed to Non-Main Functions in C  ?

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

将数组作为参数传递给非主函数时函数中,基于范围的 for 循环可能会因丢失大小信息而失败。以下是解决此问题的方法:

在提供的代码中,当将 bar 传递给 foo 时,它会衰减为指针,失去其大小。为了保留数组大小,我们可以使用数组引用类型通过引用传递它:

<code class="cpp">void foo(int (&amp;bar)[3]);

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

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

或者,我们可以使用带有自动接受任何大小的数组的模板函数的通用方法:

<code class="cpp">template <std::size_t array_size>
void foo(int (&amp;bar)[array_size]) {
  for (int i : bar) {
    cout << i << endl;
  }
}

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

通过保留数组大小信息,在将数组传递给函数时可以成功使用基于范围的 for 循环。

以上是如何在 C 中使用基于范围的 For 循环并将数组传递给非主函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn