C++ getchar_unlocked() VS scanf() VS cin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9052757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:14:17  来源:igfitidea点击:

getchar_unlocked( ) VS scanf() VS cin

c++scanf

提问by Anil Kumar Arya

What is the difference among these three input functions in programming language. Do they input in different ways from each other?

这三个输入函数在编程语言中有什么区别。他们是否以不同的方式输入?

1.getchar_unlocked()

1.getchar_unlocked()

 #define getcx getchar_unlocked

 inline void inp( int &n ) 
 {
    n=0;
    int ch=getcx();int sign=1;
    while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();}

    while(  ch >= '0' && ch <= '9' )
            n = (n<<3)+(n<<1) + ch-'0', ch=getcx();
    n=n*sign;
  }   

2.scanf("%d",&n)

2.scanf("%d",&n)

3.cin>>n

3.cin>>n

Which one takes least time when input the integers?

输入整数时,哪一个花费的时间最少?

I use THese header files in c++ where all 3 cased run in c++;

我在 c++ 中使用这些头文件,其中所有 3 个 cased 都在 c++ 中运行;

  #include<iostream>
  #include<vector>
  #include<set>
  #include<map>
  #include<queue>
  #include<stack>
  #include<string>
  #include<algorithm>
  #include<functional>
  #include<iomanip>
  #include<cstdio>
  #include<cmath>
  #include<cstring>
  #include<cstdlib>
  #include<cassert>

回答by Sobhagya Mohanty

Two points to consider.

需要考虑的两点。

  1. getchar_unlockedis deprecated in Windows because it is thread unsafe version of getchar().

  2. Unless speed factor is too much necessary, try to avoid getchar_unlocked.

  1. getchar_unlocked在 Windows 中不推荐使用,因为它是getchar().

  2. 除非太需要速度因素,否则尽量避免getchar_unlocked.

Now, as far as speed is concerned.

现在,就速度而言。

    getchar_unlocked > getchar

because there is no input stream lock check in getchar_unlockedwhich makes it unsafe.

因为没有输入流锁定检查,getchar_unlocked这使得它不安全。

    getchar > scanf

because getcharreads a single character of input which is char type whereas scanf can read most of the primitive types available in c.

因为getchar读取输入的单个字符是 char 类型,而 scanf 可以读取 c 中可用的大多数原始类型。

    scanf > cin (>> operator)

because check this link

因为检查这个链接

So, finally

所以,最后

getchar_unlocked > getchar > scanf > cin

回答by sai krishna

I had a problem in codechef that had to input many integers abd found out that the char_unlocked() is faster than scanf which is faster than cin

我在 codechef 中遇到了一个问题,必须输入许多整数 abd 发现 char_unlocked() 比 scanf 快,而 scanf 比 cin 快