gpt4 book ai didi

C++ : elegantly iterate a set of numbers

转载 作者:行者123 更新时间:2023-11-27 22:46:27 24 4
gpt4 key购买 nike

任何人都可以建议如何在 C++11/14 中优雅地迭代数字常量集(英语意思,而不是 C++ 意思),最好不要留下像这里这样的临时对象:

set<int> colors;
colors.insert(0);
colors.insert(2);

for (auto color : colors)
{
//Do the work
}

?希望能找到1-liner。

换句话说,有没有一种神奇的方法让它看起来有点像这样:

for (int color in [0,2])//reminds me of Turbo Pascal
{
//Do the work
}

for (auto color in set<int>(0,2))//Surely it cannot work this way as it is
{
//Do the work
}

最佳答案

您可以使用 std::initializer_list而不是 std::set :

for (auto color : {2, 5, 7, 3}) {
// Magic
}

封闭的大括号 { ... }将推断出 std::initializer_list<int> ,这是可迭代的。

关于C++ : elegantly iterate a set of numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42336831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com