首頁  >  文章  >  後端開發  >  如何在傳遞給 C 中非主函數的陣列上使用基於範圍的 for 迴圈?

如何在傳遞給 C 中非主函數的陣列上使用基於範圍的 for 迴圈?

Patricia Arquette
Patricia Arquette原創
2024-10-25 06:57:02276瀏覽

How can I use a range-based for-loop on an array passed to a non-main function in C  ?

傳遞給非主函數的陣列上基於範圍的for 迴圈

在C 中,基於範圍的for 迴圈可以是用於迭代數組。但是,當數組傳遞給非主函數時,它會衰減為指針,從而失去其大小資訊。

為了解決此問題並啟用基於範圍的 for 循環,陣列應該被引用而不是作為指標傳遞。這保留了數組的大小資訊。以下是示範正確方法的修改範例:

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

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

以上是如何在傳遞給 C 中非主函數的陣列上使用基於範圍的 for 迴圈?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn