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

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

Look at this code. It seems, the expected output is always 1. However, in

  • Codeforces
    • G++20
    • G++17
    • G++14
    • VC++2017
  • in my local Windows G++ 8.1.0
  • in my local Debian G++ 10.2.1

the output is always 0. In Codeforces::Clang++17 & Clang++20 the output is

Clang++
Code2

Now look at this code. Here in all previously mensioned compilers (including Clang++) the output is always 1.

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

»
21 месяц назад, # |
  Проголосовать: нравится +184 Проголосовать: не нравится

You are actually invoking undefined behavior.

The lambda on the RHS actually doesn't return bool but std::vector<bool>::reference. When the function returns, the vector goes out of scope and the attempt to read the value is UB. If you change the lambda return signature to bool or cast (bool)a[0] it'll work.

»
21 месяц назад, # |
Rev. 5   Проголосовать: нравится 0 Проголосовать: не нравится

The following update works fine on all Codeforces Custom Test C++ compilers.

Update

I often use the const auto <lambda_expression_name> = ... syntax to let the compiler infer the return-value type automatically. This works fine, except in some cases when the inferred type should be a reference and when the lambda expression is defined recursively.

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

You should prefer vector<char> to vector<bool>

»
21 месяц назад, # |
Rev. 2   Проголосовать: нравится -9 Проголосовать: не нравится

That is why I prefer to explicitly specify the return type of lambda functions.

»
21 месяц назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

function <bool()> func=[]() -> bool { solves your problem.