-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
應該給我一個索引,它的名字,我應該能夠用來索引向量。
- 爲什麼這個錯誤被拋出?
- 我知道我可以/應該使用迭代而不是C風格的索引方式,但爲了學習,我用什麼來迭代索引值,就像我在這裏試圖做的那樣?
在'的(I,V)''的是v'陰影v'的'之前的定義是你想索引的矢量。儘管您可能會優化整個循環,因爲您沒有在任何地方使用索引操作的結果。 – Lee
請不要將**答案**添加到**問題**中。我已回滾到您的原始版本,然後應用一些正常清理。歡迎您,並鼓勵,如果你認爲你有什麼實質性的添加到任何現有的答案來添加自己的答案。您還可以添加註釋,以現有的答案,如果你只是想提供更多細節少量到現有的答案。 – Shepmaster