Hacker News new | ask | show | jobs
by grepthisab 3357 days ago
I really like this. I don't like how you handle array indices though. The book is written in C++, yet you initialize all arrays where the first element is at index 1, which makes things really confusing, or at least annoying to think about when converting from your text to an IDE.
1 comments

Agreed, like it as well except hate the 1-based indexing. The first element of an array in C++ has index 0 and the last has index < n. Almost every single for loop I need in C++ has this form:

"for(int i = 0; i < n; i++)"

In this book all for loops are alien: "for(int i = 1; i <= n; i++)", and it is also accessing arrays like this here and there which would normally be out of bounds unless you make them one larger which would be very odd to do.

Very weird in an otherwise fine book.

The main point imho is that if you have a range starting at some index a, then the first element of that range is at a+0, not a+1, and if n is the amount of element of the range and a is the index of its first element, the last will be at a+n-1, not a+n. The start and end of an array is the same, an array's indexes are also a range. You may want to make it feel all natural by setting a to 1 instead of 0 for arrays, but it then becomes all messy as soon as you work with multiple ranges, especially sub ranges of an existing range since you then really need to add 0, not 1, to get the first one of that sub range, so if you want to treat your arrays the same, easiest is to also have them also start at 0. The least messy solution requiring the least subtracting of 1 to fix things is to use 0-based indexing, inclusive start index and exclusive end index such that end - start = size. But probably somebody like Dijkstra can explain it better:

"E.W. Dijkstra Archive: Why numbering should start at zero (EWD 831)": https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/E...

Looks like the indexing will be changed to 0-based in the next draft. https://github.com/pllk/cphb/commit/35d53d39d494cdc2d8f884c3...
Nice explanation, very in depth. I had to check one of the algorithms a number of times, thinking I was missing something as I couldn't see why it wouldn't iterate beyond the array. Figured it out as the initial arrays are labeled with the 1 as the first index, but as you pointed out the whole iterator changes subtley and looks alien.