jac*_*ack 3 c++ for-loop temporary
我想循环临时对的数组(指定尽可能少的类型)
for (const auto [x, y] : {{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
那可能吗?(我可以自由使用 gcc 11.2 中实现的任何 C++ 标准)
目前我正在使用maps 的解决方法,它非常冗长
for (const auto [x, y] : std::map<int, double>{{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
作为一种最小的解决方案,您可以通过显式地将初始化列表中的至少一个元素设置为 a来迭代 a std::initializer_listof s :std::pairstd::pair
for (const auto [x, y] : {std::pair{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
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}})
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,第一个元素的类型决定了其余元素的类型。例如,如果您这样做{std::pair{1, 2}, {3.1, 4.1}},最后一对将变为{3,4},因为第一对使用ints 。