C :优雅地迭代一组数字

C++ : elegantly iterate a set of numbers

本文关键字:一组 数字 迭代      更新时间:2023-10-16

任何人都可以建议在C 11/14中如何优雅地迭代数字的常数集(英语含义,而不是C 含义),最好不要在此处不留下临时对象:

set<int> colors;
colors.insert(0);
colors.insert(2);
for (auto color : colors)
{
    //Do the work
}

?希望能找到一个1线。

换句话说,是否有一种神奇的方法使它看起来有些类似:

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>,这是迭代的。

只是一些随机的想法。这样的东西?

for(auto color : set<int>{0, 2}) { // do the work }

或可能使用函数?

auto worker = [](int x) { // do the work };
worker(0);
worker(2);

要避免临时对象,也可以使用模板功能,例如

template<int N>
void worker(params_list) {
   // do the work
}

然后

worker<0>(params_list);
worker<2>(params_list);