C++ 中基於範圍的 for 迴圈
本文將介紹如何在 C++ 中使用基於範圍的 for
迴圈的多種方法。
在 C++ 中使用基於範圍的 for
迴圈來列印 std::map
的元素
基於範圍的 for
迴圈與常規 for
迴圈的可讀性更高。它可用於遍歷陣列或具有 begin
和 end
成員函式的任何其他物件。請注意,我們使用 auto
關鍵字和對該元素的引用來訪問它。在這種情況下,item
指的是 std::map
的單個元素,恰好是 std::pair
型別的元素。因此,訪問鍵值對需要特殊的點表示法以使用 first
/second
關鍵字訪問它們。
#include <iostream>
#include <map>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::map;
int main() {
map<int, string> fruit_map = {{1, "Apple",},
{2, "Banana",},
{3, "Mango",},
{4, "Cocoa",}};
for (auto &item : fruit_map) {
cout << "[" << item.first << "," << item.second << "]\n";
}
return EXIT_SUCCESS;
}
輸出:
[1,Apple]
[2,Banana]
[3,Mango]
[4,Cocoa]
或者,基於範圍的迴圈可以使用結構化繫結符號訪問元素,並使程式碼塊更簡潔。在下面的示例中,我們演示了這種繫結用法,用於訪問 std::map
對。
#include <iostream>
#include <map>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::map;
int main() {
map<int, string> fruit_map = {{1, "Apple",},
{2, "Banana",},
{3, "Mango",},
{4, "Cocoa",}};
for (const auto& [key, val] : fruit_map) {
cout << "[" << key << "," << val << "]\n";
}
return EXIT_SUCCESS;
}
輸出:
[1,Apple]
[2,Banana]
[3,Mango]
[4,Cocoa]
使用基於範圍的 for
迴圈在 C++ 中列印 struct
的成員
當遍歷的元素表示具有多個資料成員的相對較大的結構時,結構化繫結可能非常有用。如下面的示例程式碼所示,這些成員被宣告為識別符號列表,然後直接引用而沒有 struct.member
符號。請注意,大多數 STL 容器都可以使用基於範圍的 for
迴圈遍歷。
#include <iostream>
#include <list>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::list;
struct Person{
string name;
string surname;
int age;
};
int main() {
list<Person> persons = {{"T", "M", 11},
{"R", "S", 23},
{"J", "R", 43},
{"A", "C", 60},
{"D", "C", 97}};
for (const auto & [n, s, age] : persons) {
cout << n << "." << s << " - " << age << " years old" << endl;
}
return EXIT_SUCCESS;
}
輸出:
T.M - 11 years old
R.S - 23 years old
J.R - 43 years old
A.C - 60 years old
D.C - 97 years old
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