C :优雅地迭代一组数字
C++ : elegantly iterate a set of numbers
任何人都可以建议在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);
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 如何检查cin是否与数组中的一组数字匹配
- C :优雅地迭代一组数字
- 测试结果乘加减除法可能为一组数字
- 将一组数字相加或相减以达到一个值
- 需要帮助找到一组数字的数量最多和最小数量
- 如何使用伪随机数生成器生成一组特定的数字
- 查找一组数据中的最小数字
- 对一组数字进行排序的最快数据结构(和排序算法)是什么
- 查找最窄区间的算法,其中 m 将覆盖一组数字
- C++,要求用户输入一组数字求和(未知的输入数量),但是数字不会加起来
- 从一组数字中找出最接近的三个数字值
- C++ 输出一组数字的总和和乘积
- 求一组数字的GCD
- 如何将一组动作应用于一组数字
- 类似于MS Excel中的图表功能,给定一组数字,生成数学方程来描述这组数字
- 从一组集合{{中选择一组数字{1,2,3}.},{.},{.}}使得所有元素都是唯一的
- 在c++或Python中,用最少暴力的方法来查看一组数字中的多少组数字与给定的数字相加