Page List

Search on the blog

2010年6月16日水曜日

Invincible Macros for C++(1) : For Loop Macros

What kind of code do you write down with C++ when you wanna display the whole numbers from 0 up to 9?
Yup, it's quite simple.
I bet you write something like this:

----------------------------------------------------
// e.g. 1
#include <iostream>
using namespace std;

int main() {
   for (int i = 0; i < 10; i++)
      cout << i << endl;
   return 0;
}
----------------------------------------------------

That will do, but kind of cliche.
Then how's the following code?

----------------------------------------------------
// e.g. 2
#include <iostream>
#define forf(i, n) for(int i=0; i<(int)(n); i++)
using namespace std;

int main() {
   forf (i, 10)
      cout << i << endl;
   return 0;
}
----------------------------------------------------

What do you think? Guess it depends.
But the source above saves you a lot of time especially when it comes to programming contests demanding speedy conding!!

In the same way, you can utilize the macro below:
#define forb(i, n) for(int i=(int)(n)-1; i >= 0 ; i--)

0 件のコメント:

コメントを投稿