记一段神奇的代码

最近在刷一道leetcode的题的时候发现有个速度排名非常靠前的代码中有这样一段:

1
2
3
4
5
6
7
8
static const auto io_sync_off = []()
{
// turn off sync
std::ios::sync_with_stdio(false);
// untie in/out streams
std::cin.tie(nullptr);
return nullptr;
}();

老实讲,他的算法和我的几乎一样,但是就是因为多了这一段代码,他的执行时间为20ms,而我的为72ms。

在网上查阅资料后得知,这段代码是一个lambda表达式,涉及到输入输出流的缓冲与刷新同步的问题。详细分析可见:解析 static auto x = []() { std::ios::sync_with_stdio(false)\;std::cin.tie(nullptr)\;return 0\;}()

但我仍感觉这类代码意义不大,并不能真正提高解决问题的能力,而是通过加快测试用例的输入与结果的输出速度来欺骗leetcode的评审机制罢了。