首页 > 后端开发 > C++ > 正文

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

Barbara Streisand
发布: 2024-10-25 03:01:30
原创
118 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!