tags:

views:

815

answers:

8

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);
}
A: 
void DoSomethingRepeatedly(int numTimesTo Loop)
{
   for(int i=0; i<numTimesToLoop; i++)
   { 
       //do whatever; 
   }
}

That it ? That can't be.. too simple.. I must be misunderstanding your question :( Of course you'd have to check that the value of numTimesToLoop is >= 0.

Edit: I made it a method, just in case.

FOR
+5  A: 

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.

Konrad Rudolph
Yes, a standard `for` loop or an STL `for_each` is much preferred over cpp macros.
Pat Notz
+8  A: 
#define superFor(n) for(int i = 0; i < (n); i++)

Edit: Be careful to not use another variable called i in the loop.

A: 

Maybe BOOST_FOREACH will do what you want:

http://engineering.meta-comm.com/resources/cs-win32_metacomm/doc/html/foreach.html

Scott Langham
A: 

Try recursion:

superFor(int numTimes) { if (numTimes > 0) doSomethingMeaningful(); superFor(--numTimes) }

chris
superFor(0xffffffff); Stack Overflow!!!
Skizz
A: 

You could use a macro.

#define superFor(v,i) for(int v=0; v<(i); v++)

and use it like this:

superFor(i,10) {
   printf("Doing something ten times");
}
Hafthor
+2  A: 

It's crazy, but it might just work...

http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html.

Daniel Earwicker
+2  A: 

in C++ you do that with a regular for-loop.

  for(variable; condition; increment) {
    //stuff goes here
  }

In your for-loop: variable is a counting variable like i. You can define the variable right here and initialize it. You often see something like "int i = 0"

condition is some sort of test. In your case you want to check if your counting variable is less than how many times you want the loop to execute. You'd put something like "i < how_many_times_to_loop"

increment is a command to increment the counting variable. In your case you want "i++" which is a short hand way of saying "i = i + 1"

So that gives us:

  for(int i = 0; i < how_many_times_to_loop; i++) {
    //stuff goes here
  }
Keith Twombley