2016-12-15 87 views
-1

我嘗試使用下面的代碼來衡量Vec[]編制索引與.get(index)速度:如何解決「不能索引`usize`類型的值的錯誤?

extern crate time; 

fn main() { 
    let v = vec![1; 1_000_000]; 
    let before_rec1 = time::precise_time_ns(); 

    for (i, v) in (0..v.len()).enumerate() { 
     v[i] 
    } 
    let after_rec1 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec1 - before_rec1); 


    let before_rec2 = time::precise_time_ns(); 

    for (i, v) in (0..v.len()).enumerate() { 
     v.get(i) 
    } 
    let after_rec2 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec2 - before_rec2); 
} 

但這返回以下錯誤:

error: cannot index a value of type `usize` 
--> src/main.rs:8:9 
    | 
8 |   v[i] 
    |   ^^^^ 

error: no method named `get` found for type `usize` in the current scope 
    --> src/main.rs:17:11 
    | 
17 |   v.get(i) 
    |   ^^^ 

我很困惑,爲什麼這個不起作用,因爲enumerate應該給我一個索引,它的名字,我應該能夠用來索引向量。

  1. 爲什麼這個錯誤被拋出?
  2. 我知道我可以/應該使用迭代而不是C風格的索引方式,但爲了學習,我用什麼來迭代索引值,就像我在這裏試圖做的那樣?
+3

在'的(I,V)''的是v'陰影v'的'之前的定義是你想索引的矢量。儘管您可能會優化整個循環,因爲您沒有在任何地方使用索引操作的結果。 – Lee

+1

請不要將**答案**添加到**問題**中。我已回滾到您的原始版本,然後應用一些正常清理。歡迎您,並鼓勵,如果你認爲你有什麼實質性的添加到任何現有的答案來添加自己的答案。您還可以添加註釋,以現有的答案,如果你只是想提供更多細節少量到現有的答案。 – Shepmaster

回答

6

你,朋友,在這裏是非常困惑。

fn main() { 
    let v = vec![1; 1_000_000]; 

v的類型爲Vec<i32>

for (i, v) in (0..v.len()).enumerate() { 
    v[i] 
} 

你迭代的一系列指標,從0v.len(),並使用enumerate生成指數,當您去:

  • v的類型爲usize
  • 在循環中,v == i ,總是

所以......確實,編譯器是正確的,你不能在usize上使用[]


程序「固定」:

extern crate time; 

fn main() { 
    let v = vec![1; 1_000_000]; 

    let before_rec1 = time::precise_time_ns(); 

    for i in 0..v.len() { 
     v[i] 
    } 

    let after_rec1 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec1 - before_rec1); 


    let before_rec2 = time::precise_time_ns(); 

    for i in 0..v.len() { 
     v.get(i) 
    } 

    let after_rec2 = time::precise_time_ns(); 
    println!("Total time: {}", after_rec2 - before_rec2); 
} 

我想補充一個免責聲明,不過,如果我是一個編譯器,這個沒用的循環將被優化成一個空操作。如果在與--release編譯後,您的程序報告0,這就是發生了什麼。

鏽病內置benchmarking support,我建議你使用它,而不是去用簡單的方式。而且......你還需要檢查發射的組件,這是確保你測量自己的想法的唯一方法(優化編譯器就像那樣棘手)。

相關問題