如何在C ++中创建一个for循环像命令? [英] How to create a for loop like command in C++?
问题描述
我想在C ++中做一些非常简单的事情,但我找不到方法。
我想创建一个类似于for循环的函数,我将理想地为迭代应该发生的时间输入一个变量,并且我的函数将在括号内执行一些函数。我希望我很清楚。谢谢...
示例
superFor(1)
{
//在这里执行的命令
add(1 + 2);
因为(语言的当前版本)缺少这里需要的一些功能:即创建功能块即时。
您可以做的是将函数指针或函数对象传递给你的函数。 STL提供了很多这方面的例子。考虑:
void out(int x){
cout<< x<< '';
}
vector< int> XS;
xs.push_back(42);
xs.push_back(23);
for_each(xs.begin(),xs.end(),out);
它将函数 out
的指针传递给函数 for_each
。 p>
I want to do something very simple in C++ but i can't find how. I want to create a function like a for loop where i will ideally enter a variable for the times the iteration should happen and some functions inside brackets my function will execute. I hope i was clear enough. Thanks...
Example
superFor (1)
{
//commands to be executed here
add(1+2);
}
What you want isn't possible in C++ because the (current version of the) language lacks some features that are required here: namely, creating function blocks "on the fly".
The best you can do is pass a function pointer or function object to your function. The STL offers many examples of this. Consider:
void out(int x) {
cout << x << ' ';
}
vector<int> xs;
xs.push_back(42);
xs.push_back(23);
for_each(xs.begin(), xs.end(), out);
This passes a pointer to function out
to the function for_each
.
这篇关于如何在C ++中创建一个for循环像命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!