看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 問題(Question): 我本來以為auto可以這樣用,不過這種情況似乎不太適用?? 我想要全程使用auto幫我推導,不過vector的size是unsigned我直接這樣用有問題 以我的範例難道我還是只能自己指定j的型態嘛(int) 有比較正確auto的方式嘛??感覺都會推導錯誤?? 預期的正確結果(Expected Output): test 1 test 0 錯誤結果(Wrong Output): 無窮迴圈 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) #include <iostream> #include <vector> using namespace std; int main(){ vector<int> ans = {1,2,3}; auto n = ans.size(); for(auto j = n - 2;j >= 0;--j)//改成int j = n -2就ok { printf("test %ld\n",j); } } ※ 編輯: WangDaMing (36.230.5.115 臺灣), 11/02/2021 23:12:51
mikemike1021: 因為 auto 會導致他是 unsigned,0-1不會是負數,導 11/02 23:16
mikemike1021: 致你的迴圈條件永遠成立,所以會是無窮迴圈 11/02 23:16
mikemike1021: 或者你迴圈條件也可以改成 j < j + 1 11/02 23:20
aiwhat: unsigned 和 signed 變數比較時會轉型成 unsigned 11/03 00:38
aiwhat: vector::size 回傳 unsigned → j = n - 2 也是 unsigned 11/03 00:39
peter98: Size() returns unsigned 11/03 03:04
chchwy: 自動推導的j是無號數阿 無號數怎麼可能會小於零呢? 11/03 09:54
chchwy: 所以你的for loop條件永遠都成立 無法離開回圈 11/03 09:55
b0920075: 推導錯誤x 你寫錯o 11/03 12:59
KevinR: 推導錯誤X 你用錯○ 11/03 13:57
a27417332: 借串問,好奇對於這種unsigned然後往下數的狀況 11/03 15:17
a27417332: 通常for裡面會怎麼寫? 11/03 15:17
nh60211as: 不要往下數或是用reverse iterator 11/03 15:43
sarafciel: 1.你如果不知道型態 最好不要用auto 11/03 19:45
sarafciel: 2. 你如果不知道發生什麼事 最好也不要講推導錯誤 11/03 19:46
WangDaMing: 感謝以上各位大大~其實我是想問這有沒有較好的寫法 11/03 23:30
WangDaMing: 還是就真的不知道size的型態不要隨便用auto...Orz 11/03 23:31
ketrobo: 不知道就學一下const iterator,粉好用 11/04 00:01
tomsawyer: 我的話 覺得auto拿來接iterator可以少打字 lol 11/04 01:39
NciscalA: for_each + reverse iterator 11/04 09:28
a27417332: 萬一是需要index呢?該不會用rev iter+額外index吧? 11/04 19:46
nh60211as: 可以用std::distance 11/04 19:48
chchwy: 真的要往下數...就用int啊,不要auto推導就好了 11/05 07:30
firejox: 用 c++20 的 ssize https://godbolt.org/z/rbrPfa51d 11/05 10:35
steve1012: 不要濫用auto 就解決了 11/05 13:12
steve1012: type information很好用 除非真的很有幫助 (e.g. iter 11/05 13:12
steve1012: erator type name 很長) 最好都直接寫type name 11/05 13:12
Dracarys: 它照你打的執行沒有錯啊 unsigned沒問題 推導沒有錯 11/07 23:45
alex780312: 同一行就知道型態時可以auto一下,例如auto ptr =ma 11/09 07:37
alex780312: ke_unique<MyClass>(…); 11/09 07:37
alex780312: 我是建議不要自己把size_t和unsigned 互換,是長度就 11/09 07:46
alex780312: 維持size_t。甚至要用using MyNumber = int;的方式確 11/09 07:46
alex780312: 保不會讓所有函數都吃最基本形態而看不出是啥東西。 11/09 07:46
alex780312: 早起的NULL 變成現在nullptr 也是一個可以學習的例子 11/09 07:46
alex780312: 形態名字太長可以用using改善,auto是避免冗余描述, 11/09 07:55
alex780312: 例如使用template 時的例子 11/09 07:55
Dracarys: 最近看到一本C的書是這樣寫,一樓也有提到,>=改成<=: 01/11 08:56
Dracarys: https://godbolt.org/z/eqec86jTE 01/11 08:56