C 重复N迭代

c++ repeat N iterations

本文关键字:迭代 重复      更新时间:2023-10-16

我可以清楚地做类似的事情:

for(int i = 0; i < 10000; i++)
    testIteration();

但是有没有一个性质的功能在一行中可以做类似的事情?这样的东西:

std::repeat(10000, testIteration);

在C 的拟议标准中,有一个示例iota_view

for (int i : iota_view{1, 10})
  cout << i << ' '; // prints: 1 2 3 4 5 6 7 8 9

但目前可以使用范围V3库:

for (int _ : view::iota{0, 10})
    testIteration();            // calls testIteration 10 times.

我个人喜欢使用一个小的辅助功能来做到这一点。

template <typename F>
void repeat(size_t n, F f) {
  while (n--) f();
}
int main() {
   repeat(1000, [&] {
      testIteration();
   });
}

这避免了必须拼出变量的名称。当我需要一个名称时,我更喜欢使用view :: iota。

话虽如此,我被告知这是令人困惑的阅读,每个人都可以 阅读for循环,所以这可能是要走的路。(当然,除非将功能放入std ::)。

但是是否有任何性病功能在一行中可以使用类似的功能?

不,标准库中没有算法可以执行此操作(至少没有任何不需要编写无用的样板)。正如其他人已经提到的那样,循环是做"某件事" n-times的最可读性和最不混淆的方法。

话虽如此,如果您将其作为练习来获得更多简短的语法,则可以写下:

#include <iostream>
struct my_counter {    
    int stop;
    struct iterator {
        int count;    
        iterator& operator++() { ++count; return *this; }
        int operator*() { return count;}
        bool operator!=(const iterator& other) { return count != other.count; }
    };
    iterator begin() { return {0}; }
    iterator end() { return {stop};}    
};
void print() { std::cout << "x"; }
int main() {
     for (auto x : my_counter{5}) print();
}

但是,我强烈建议不要使用类似的东西。每个人都知道循环是如何工作的以及它的作用。除非有标准算法,否则可以眨眼间读取循环,而其他任何事物都不常见,令人惊讶和混淆(尽管我怀疑这种特定情况的算法是否会极大地使用)。当您可以使用循环时,为什么还要重新发明轮子?

我知道这不是从上述答案中提供任何新的答案,除了我的解决方案是非常短的。要重复代码 2 时间,我使用以下循环:

for (auto _{2}; _--;) { /* this code gets repeated twice */ }

我认为使用前缀操作员会不太清楚,因为要重复两次循环需要:

for (auto _{3}; --_;) { /* this code gets repeated twice */ }

括号当然也可以工作而不是牙套,即:

for (auto _(2); _--) {}

仅供参考,可以使用std::generatestd::generate_n,但仅通过执行类似的操作来用于数组初始化:

int i = 0;
std::generate_n(myArray, 10000, [&]() -> int { return i++; });

简单地定义宏怎么样? #define FOR(N, foo, ...) for (int _i = 0; _i < N; _i++) foo(__VA_ARGS__);

例如。

#include <iostream>
#define FOR(N, foo, ...) for (int _i = 0; _i < N; _i++) foo(__VA_ARGS__);
void bar(int a, int b)
{
    std::cout << "hello " << a+b << std::endl;
}
int main()
{
    FOR(5, bar, 12, 6);
    return 0;
}

输出:

hello 18
hello 18
hello 18
hello 18
hello 18