Yeah, that code you have there works. It's not how I personally would have done it, but there's nothing
wrong with it.
And lastly as to why my original code wasn't working correctly, I have a guess now after watching the guy bounce numbers in and out of the array. My guess is my code was adding into index 0, asking the second loop to check, it saw it's own 0 + 1 index filled with that element, saw it as equal, and continued doing that through every iteration. At no point was I asking it to empty the container that stored the duplicate. Possibly? |
No. It's because your original loop on lines 8-17 was checking if there were any pairs of duplicate numbers
in the entire array. But there was no guarantee that the array had been set to anything after 'count'. For example, if human() was called like this:
1 2
|
int array[5];
human(array, 5);
|
the contents of array are undefined. Some execution environments initialize uninitialized stack memory to specific values (e.g. Visual Studio in debug mode initializes it to 0xCC). If you were using MSVC, that array would have been filled with -858993460.
By the way "undefined" in C and C++ isn't a distinct value like in JavaScript or other scripting languages. When C and C++ people talk about something being undefined, they're saying that the language gives no guarantees about that thing.
When a value is undefined, reading it will give something unpredictable until you actually run it:
1 2
|
int this_is_undefined;
std::cout << this_is_undefined;
|
When a behavior is undefined, it becomes impossible to reason about what the program will do. The language allows a program with undefined behaviors to do anything.
1 2 3
|
int *dont_write_to_me;
*dont_write_to_me = 42;
//Now anything can happen. Literally anything!
|