C ++代码中奇怪的未使用静态字符串声明 [英] Weird unused static string declaration in C++ code

查看:73
本文介绍了C ++代码中奇怪的未使用静态字符串声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,在一个受欢迎的问题解决站点中,我提交了一个问题的解决方案,然后查找了一个更快的代码,以查明他/她的代码比我的代码运行得更快的原因.总体算法是相同的,但是我发现的主要区别如下.

Today in a popular problem solving site, i submitted a solution for a problem, then looked up a more faster code to find out what is the reason that his/her code is running faster than mine. The overall algorithm was same but the main difference i found is following.

static string x = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return "";
}();

我也不明白cin.tie(nullptr)在这里做什么.我读到了

I also didn't understand what cin.tie(nullptr) doing here. I read about

ostream *领带(ostream * tiestr);

但无法弄清楚这行在这里做什么.

but couldn't figure out what this line is doing here.

请注意,我已经知道std::ios::sync_with_stdio(false)不再浪费时间将printf/scanf的I/O操作与C ++计数器部件cin/cout同步的事实.

Note that i've already know the fact that std::ios::sync_with_stdio(false) stop wasting time to sync the i/o operation of printf/scanf with C++ counter part cin/cout.

我已经猜到了,甚至在主函数运行之前,块中的代码就已经执行了,但是我不知道该构造背后的真正原因是什么.

I've already guessed that, the code inside the block get executed before even the main function ran, but i've no clue that what is the actual reason behind this construct.

对不起,我的英语不好,非常感谢您的帮助.

Sorry for my bad english, your help will be greatly appreciated.

推荐答案

您已经猜到了大多数:

  • 通过使用lambda初始化静态变量来在main之前执行
  • 它禁用与I/O相关的操作,这些操作会减慢执行速度:
    • std::ios::sync_with_stdio
    • cin.tie(nullptr)将从cout解除cin的绑定.见下文
    • it is executed before the main by initializing a static variable using a lambda
    • it disables i/o related things that will slow down execution:
      • std::ios::sync_with_stdio
      • cin.tie(nullptr) will untie cin from cout. See below

      来自cplusplus.com:

      from cplusplus.com:

      绑定流是一个输出流对象,该对象在刷新之前 该流对象中的每个I/O操作

      The tied stream is an output stream object which is flushed before each i/o operation in this stream object

      我想这个问题需要来自cin的输入,而您在cout上提供了答案,从现在开始,写入cout会更快.

      I guess this problem takes input from cin and you provide the answer on cout, from this point onward, writing to cout will be faster.

      这篇关于C ++代码中奇怪的未使用静态字符串声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆