2012-01-29 78 views
11

是什麼編程語言這三種輸入功能之間的差異。 他們以不同的方式輸入彼此嗎?getchar_unlocked()VS scanf()的VS CIN

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)

3.cin>>n

哪一個花費最少的時間,當輸入整數?

我使用在C++這些頭文件,其中所有3套管運行在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> 
+0

當C++編程,你想用'cin'。自從您提供了C和C++標籤以來,很難給出一個很好的答案。你在使用哪一個?他們不是同一種語言。 – 2012-01-29 12:04:24

+1

刪除了'C'標記,因爲'cin'不存在C.其中 – 2012-01-29 12:08:21

回答

4

我在codechef一個問題,即必須輸入許多整數ABD發現該char_unlocked()比scanf函數比CIN

+0

顯式地指出一個問題「數據集是巨大的,使用速度更快的I/O的方法。」:http://uva.onlinejudge.org/ external/124/12440.html](http://uva.onlinejudge.org/external/124/12440.html) – thiagowfx 2013-05-26 03:20:59

26

兩點考慮快了快了。

  1. getchar_unlocked在Windows反對,因爲它是getchar()線程不安全的版本。

  2. 除非速度的因素太多必要,儘量避免getchar_unlocked

現在,就速度而言。

getchar_unlocked > getchar 

,因爲在沒有getchar_unlocked輸入流鎖定檢查這使得它是不安全的。

getchar > scanf 

因爲getchar讀取輸入的一個單獨的字符是字符類型而scanf的可以讀取最原始類型的可用的在C。

scanf > cin (>> operator) 

,因爲這種檢查link

所以,最後

getchar_unlocked > getchar > scanf > cin 
+0

我沒有得到這個比較:** getchar_unlocked> getchar> scanf> cin **,因爲除了'cin '(這是一個對象),所有其他的都是函數。比較功能速度是有道理的。但是,如何將函數與對象進行比較?它甚至沒有意義。然而,你可以將這些函數與'cin'支持比較,例如'operator >>'重載和'read()',它們有不同的折衷,例如'read()'比'operator >>'快,但它不會' t格式化緩衝區。 – Nawaz 2015-08-14 06:13:51

+0

@Nawaz答案是在問題的上下文中明確指出功能之間的比較。 – 2015-08-15 13:00:53

+0

你沒有比較功能,就是我說的。 – Nawaz 2015-08-15 13:05:06