Блог пользователя LelouchRiBritannia

Автор LelouchRiBritannia, история, 8 лет назад, По-английски

Could someone give me some advice?

In Pascal, I usually see people using one-based index.
But in C++, everyone prefers zero-based index.

I know each has its own advantages.
I find it hard to use one-based index in forming formulas because I have to add and subtract 1 all the times.
In zero-based index, this is not a problem but sometimes because the first element is zero, so if I want to use some initial values I have to set it to negative, for examples -1, but the issue is I have to check the overflow of the value because I cannot index negative value.

I want to get used to just one type, so anybody can give me more ideas before I do it?
Thank you.

  • Проголосовать: нравится
  • +23
  • Проголосовать: не нравится

»
8 лет назад, # |
Rev. 2   Проголосовать: нравится +37 Проголосовать: не нравится

Since you know each has its own advantages. Why do you want to use only one? My suggestion is to choose one which is more convenient based on the scenario.

Usually I prefer zero-based index. Because (at least for me) for(int i=0;i<n;++i) and sort(a,a+n) is more convenient than for(int i=1;i<=n;++i) and sort(a+1,a+1+n). At the same time, they are more consistent with the C++ style. But if a problem requires much use of one-based indices or I need a boundary/sentinel zero position, I would use one-based index.

If you must choose one, maybe you should use one-based index, since sometimes it would be pretty painful without the zero position.

BTW: you can use negative array index if it is really necessary (not a good idea for just to get the -1 position), to use that, you can write something like:

int _dp[2333],*dp=_dp+1111;
dp[-666]=1;