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

Автор ahnaf09, история, 15 месяцев назад, По-английски

Hi everyone,

While solving Problem 2107A - LRC и VIP, I got stuck and decided to read the editorial. In the editorial solution, I came across the following line:

for (int i = 0; i < n; ++i)
    cout << (1 + (a[i] == mx)) << " \n"[i + 1 == n];

I have a basic understanding that the expression (a[i] == mx) returns a boolean value, and when it's true, it becomes 1, so the full expression would be 1 + 1 = 2; otherwise, 1 + 0 = 1.

However, I'm not fully sure about the use of " \n"[i + 1 == n]; — I assume it’s a trick to conditionally print either a space or a newline depending on whether it’s the last element in the loop.

Can someone please explain this line step-by-step? I'd really appreciate any clarification.

Thanks in advance.

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

»
15 месяцев назад, скрыть # |
Rev. 2  
Проголосовать: нравится +3 Проголосовать: не нравится

think of " \n" as a string and [i+1 == n] will eventually evaluate to 0 or 1, resulting in accessing the 0th or 1st index of the string.

»
15 месяцев назад, скрыть # |
 
Проголосовать: нравится -6 Проголосовать: не нравится

you got it right, although you can use gpt and other LLMs to resolve these simple doubts. A blog must be the end resort.