C++17 结构化绑定(Structured Binding) 的范围 for 循环
在 C++17 中,结构化绑定(Structured Bindings)可以与范围 for 循环结合使用,简化对容器元素的访问。以下是几种常见场景的代码示例:
示例 1:遍历 std::map(键值对)
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> users = {
{101, "Alice"},
{102, "Bob"},
{103, "Charlie"}
};
// 结构化绑定解构 pair<const Key, Value>
for (const auto& [id, name] : users) {
std::cout << "ID: " << id << ", Name: " << name << "\n";
}
// 输出:
// ID: 101, Name: Alice
// ID: 102, Name: Bob
// ID: 103, Name: Charlie
}
示例 2:遍历 std::vector 中的 std::pair
#include <iostream>
#include <vector>
#include <utility> // for std::pair
int main() {
std::vector<std::pair<std::string, int>> scores = {
{"Math", 90},
{"Physics", 85},
{"Chemistry", 92}
};
// 解构 pair 的 first 和 second
for (const auto& [subject, score] : scores) {
std::cout << subject << ": " << score << " points\n";
}
// 输出:
// Math: 90 points
// Physics: 85 points
// Chemistry: 92 points
}
示例 3:遍历自定义结构体的数组
#include <iostream>
#include <vector>
struct Point3D {
double x, y, z;
};
int main() {
std::vector<Point3D> points = {
{1.0, 2.0, 3.0},
{4.0, 5.0, 6.0}
};
// 解构结构体的成员
for (const auto& [x, y, z] : points) {
std::cout << "(" << x << ", " << y << ", " << z << ")\n";
}
// 输出:
// (1, 2, 3)
// (4, 5, 6)
}
示例 4:遍历 std::array 或原生数组
#include <iostream>
#include <array>
int main() {
std::array<std::string, 2> names = {"Alice", "Bob"};
// 解构数组元素
for (const auto& [first_char, rest] : names) {
// 注意:此例仅为演示,实际需确保字符串长度足够
if (!first_char.empty()) {
char f = first_char[0];
std::string r = first_char.substr(1);
std::cout << "First: " << f << ", Rest: " << r << "\n";
}
}
// 输出:
// First: A, Rest: lice
// First: B, Rest: ob
}
示例 5:遍历嵌套容器(tuple/pair)
#include <iostream>
#include <tuple>
#include <vector>
int main() {
std::vector<std::tuple<int, double, std::string>> data = {
{42, 3.14, "Pi"},
{1729, 2.718, "e"}
};
// 解构 tuple 的三个元素
for (const auto& [id, value, symbol] : data) {
std::cout << id << ": " << symbol << " ≈ " << value << "\n";
}
// 输出:
// 42: Pi ≈ 3.14
// 1729: e ≈ 2.718
}
关键点总结:
- 语法:
for (auto&& [var1, var2, ...] : container) - 适用类型:
- 数组、
std::array、std::pair、std::tuple - 所有公开成员的简单结构体(隐式支持)
- 定义了
get()方法的自定义类型(显式支持)
- 数组、
- 引用修饰符:
auto&:修改元素(非 const 容器)const auto&:只读访问(推荐)auto:拷贝元素(可能低效)
通过结构化绑定,代码更简洁且可读性更高,避免了手动访问 .first/.second 或成员变量的繁琐操作。
浙公网安备 33010602011771号