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
You are actually invoking undefined behavior.
The lambda on the RHS actually doesn't return
bool
butstd::vector<bool>::reference
. When the function returns, thevector
goes out of scope and the attempt to read the value is UB. If you change the lambda return signature tobool
or cast(bool)a[0]
it'll work.The following update works fine on all Codeforces Custom Test C++ compilers.
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.https://stackoverflow.com/questions/8399417/why-vectorboolreference-doesnt-return-reference-to-bool
You should prefer
vector<char>
tovector<bool>
That is why I prefer to explicitly specify the return type of lambda functions.
function <bool()> func=[]() -> bool {
solves your problem.