Reputation: 133
I'm a competitive programmer, and I've been asking myself if there is any shorter, more elegant way of writingfor(int i=0; i<n; ++i)
. I can only use standard C++, no other libraries.
Upvotes: 2
Views: 107
Reputation: 51
I'm a competitive programmer too. This answer may be off-topic, but I think it will provide some useful ideas.
Personally, I think you shouldn't focus on these types of questions. I don't think there's a big difference between writing for (int i = 1; i <= n; ++i)
and FOR(i, 1, n)
. The first one is obviously shorter and takes less time to type, but once you get to a high enough level, problem-solving skills matter much much more than typing speed. Don't trust me? See tourist's code.
I think what you should focus on is improving your problem-solving skills. The best way is to solve as many problems as possible. Doing so will also increase your typing speed as a side effect.
Upvotes: 0
Reputation: 2601
In c++ competitions there is well known set of macros (don't use it in commercial projects). You also asked for more elegant solution (it is well known solution, but for sure not more elegant)
For example read this topcoder website:
#define REP(x, n) for(int x = 0; x < (n); ++x)
then in code you can simply write
REP(i,n){
}
One basic complete header I found:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
typedef vector<int> VI;
typedef long long LL;
#define FOR(x, b, e) for(int x = b; x <= (e); ++x)
#define FORD(x, b, e) for(int x = b; x >= (e); – –x)
#define REP(x, n) for(int x = 0; x < (n); ++x)
#define VAR(v, n) typeof(n) v = (n)
#define ALL(c) (c).begin(), (c).end()
#define SIZE(x) ((int)(x).size())
#define FOREACH(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define PB push_back
#define ST first
#define ND second
Upvotes: 1
Reputation: 7493
Seeing you didn't specify whether you need to use i
how about[1]:
int i=n+1; while(--i);
Its shorter!
[1] not proven to be correct.
Upvotes: 0
Reputation: 1450
Without running timed tests, I would assume that both:
for(int i=0; i<n; ++i)
and:
int i=0;
while (i<n)
{
i++
}
would be extraordinarily close in timing. Perhaps use timestamps within a program that runs both types of loops, and see what the overall time/loop is for each type.
These are the fundamental looping structures of C / C++, so I do not think there would be something that would run faster (but I'm willing to be wrong if I learn something new)
Upvotes: 0