C 重复N迭代
c++ repeat N iterations
我可以清楚地做类似的事情:
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::generate
和std::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
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 嵌套循环和重复迭代器
- 我怎样才能在不重复的情况下随机迭代向量的每个元素
- 重复输出的类型是怎么回事,它如何区分迭代次数和 Ascii 代码?
- 将迭代器范围复制到矢量而不重复
- 避免以不同的迭代剂的循环循环避免几乎相同的代码重复
- C 重复N迭代
- C++初学者-当循环重复第一次迭代时
- 输入迭代器可以重复读取,而输出迭代器只能写入一次
- 如何在迭代后重复从主函数重复执行
- 如何记录C 重复迭代函数的总时间
- 迭代循环重复的次数比我预期的要多
- 在实现迭代器和const_iterator类时避免代码重复的最佳实践
- 如何避免代码重复或多次迭代
- C++ 集合、迭代器、查找发现重复项的行的用法
- 在编写迭代器和const_iterator时避免代码重复
- c++有一种方法可以将优先级队列元素复制到vector中,这样就可以对其进行迭代以检查是否有重复项