如何遍历临时对

How to iterate over temporary pairs

我想遍历一个临时对数组(指定尽可能少的类型)

for (const auto [x, y] : {{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
  // ...
}

这可能吗? (我可以自由使用在 gcc 11.2 中实现的任何 C++ 标准)

目前我正在使用 maps 的解决方法,它非常冗长

for (const auto [x, y] : std::map<int, double>{{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
  // ...
}

作为最小的解决方案,您可以通过显式地使初始化列表的至少一个元素成为 std::pair:

来迭代 std::pairstd::initializer_list
for (const auto [x, y] : {std::pair{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
  // ...
}

Demo 上天了。

std::map进行堆分配,有点浪费。 std::initializer_list<std::pair<int, double>> 在这方面更好,但更冗长。

更明智的选择:

for (const auto [x, y] : {std::pair{1, 1.0}, {2, 1.1}, {3, 1.2}})

请注意,在这种情况下,第一个元素的类型决定了其余元素的类型。例如。如果你这样做 {std::pair{1, 2}, {3.1, 4.1}},最后一对变成 {3,4},因为第一对使用 ints.