如何在 C++ 中迴圈遍歷陣列
本文將說明如何使用 C++ 中的不同方法遍歷陣列。
使用 for
迴圈在陣列上迭代的方法
對陣列元素進行遍歷的一個明顯可見的方法是 for
迴圈。它由三部分語句組成,每一部分用逗號分隔。首先,我們應該初始化計數器變數-i
,根據設計,它只執行一次。接下來的部分宣告一個條件,這個條件將在每次迭代時被評估,如果返回 false
,迴圈就停止執行。在這種情況下,我們比較計數器和陣列的大小。最後一部分遞增計數器,它也在每個迴圈週期執行。
#include <iostream>
#include <array>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::array;
int main() {
array<string, 10> str_arr = {"Albatross", "Auklet",
"Bluebird", "Blackbird",
"Cowbird", "Dove",
"Duck", "Godwit",
"Gull", "Hawk"};
for (size_t i = 0; i < str_arr.size(); ++i) {
cout << str_arr[i] << " - ";
}
cout << endl;
return EXIT_SUCCESS;
}
輸出:
Albatross - Auklet - Bluebird - Blackbird - Cowbird - Dove - Duck - Godwit - Gull - Hawk -
使用基於範圍的迴圈來迭代一個陣列
基於範圍的迴圈是傳統 for
迴圈的可讀版本。這種方法是一種強大的替代方法,因為它在複雜的容器上提供了簡單的迭代,並且仍然保持了訪問每個元素的靈活性。下面的程式碼示例是前面例子的精確再實現。
#include <iostream>
#include <array>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::array;
int main() {
array<string, 10> str_arr = {"Albatross", "Auklet",
"Bluebird", "Blackbird",
"Cowbird", "Dove",
"Duck", "Godwit",
"Gull", "Hawk"};
for (auto &item : str_arr) {
cout << item << " - ";
}
cout << endl;
return EXIT_SUCCESS;
}
使用 std::for_each
演算法遍歷陣列
for_each
是一個強大的 STL 演算法,用於操作範圍元素和應用自定義定義的函式。它將範圍起始和最後一個迭代器物件作為前兩個引數,函式物件作為第三個引數。本例中,我們將函式物件宣告為 lambda
表示式,直接將計算結果輸出到控制檯。最後,我們可以將 custom_func
變數作為引數傳遞給 for_each
方法,對陣列元素進行操作。
#include <iostream>
#include <array>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::array; using std::for_each;
int main() {
array<int, 10> int_arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto custom_func = [](auto &i) { cout << i*(i+i) << "; "; };;
for_each(int_arr.begin(), int_arr.end(), custom_func);
cout << endl;
return EXIT_SUCCESS;
}
輸出:
2; 8; 18; 32; 50; 72; 98; 128; 162; 200;
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn