C++ 的 结构化绑定

等级 5404 次按键

使用 C++17 结构化绑定,把 map 的元素拆为 name 和 score,把结构体拆为三个成员,把 insert() 返回的 pair 拆为迭代器和 bool。

C++ 代码

// 含有三个公有成员的简单结构体
1struct Point {
2 double x, y, z;
3};
4
// map 按键的顺序保存
5map<string, int> scores = {{"Alice", 95}, {"Bob", 87}, {"Carol", 92}};
6
// 每个元素是 pair,被拆成键和值
7for (const auto& [name, score] : scores) {
// 按键的顺序输出:Alice、Bob、Carol
8 cout << name << ": " << score << endl;
9}
10
// 对结构体进行聚合初始化
11Point p = {1.5, 2.5, 3.5};
// 按声明顺序拆出成员 x、y、z
12auto [px, py, pz] = p;
// 输出“Point: (1.5, 2.5, 3.5)”
13cout << "Point: (" << px << ", " << py << ", " << pz << ")" << endl;
14
// insert 返回 pair<iterator, bool>;bool 表示键是否为新插入
15auto [it, inserted] = scores.insert({"Dave", 88});
// “Dave”是新键,因此输出“Inserted: 1”(未用 boolalpha 时的 true)
16cout << "Inserted: " << inserted << endl;

运行结果

Alice: 95
Bob: 87
Carol: 92
Point: (1.5, 2.5, 3.5)
Inserted: 1
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • <× 31
  • "× 20
  • ,× 17
  • ;× 9
  • {× 8
  • }× 8
  • :× 4
  • .× 4
  • =× 4
  • (× 3

C++ 等级 5 的更多代码示例

← 返回 C++ 打字练习