[Solved] Can someone explain this C++ code? [closed]


If i equals 0, then you can’t look words[i-1] because you can’t do words[-1]

Furthermore, when you use || operator, if the first expression is true, the second expression is not checked

With i == 0 || words[i - 1] != words[i] you can print your first words because i equals 0 and the expression words[i - 1] != words[i] isn’t checked and doesn’t crash your program !
then with i different from 0, the first expresion isn’t true and the second is checked.


For the unrepetition part :

Your array is sorted, so same words are one after another.
Then you have to check if the previous word isn’t the same, you can print the word


How words[i - 1] != words[i] works :

for std::string, operators == and != look for the length of each string, and each character in the string

Comparison operator for std::string

Moreover, words[i-1] look for the previous words, and words[i] for the current one, to compare them.

So here, the expression is true if the two consecutives words aren’t the same, in length and letters.
if you have words dog cat cat cat_ in your array, dog is printed first (because of the i == 0 part), the second word cat is printed, then the epression is false because the words are identical ("cat" == "cat"), and finaly, cat_is printed because different from cat

2

solved Can someone explain this C++ code? [closed]