看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) OSX El Capitan 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) Homebrew GCC 7.2.0 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) C++ 預設 STL 問題(Question): 我想要把資料傳入function後,他再依據傳入的值,去執行該做的事 結束後把state改掉,這樣在接下來的時候就不會走到同樣的state 餵入的資料(Input):預期的正確結果(Expected Output): 0 9 8 7 6 5 4 3 2 1 錯誤結果(Wrong Output): 0 9 0 7 6 terminated by signal SIGSEGV (Address boundary error) 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) #include <iostream> #include <vector> using namespace std; vector<int> arr; int obov(){ arr.push_back(0); return arr.size()-1; } void myfunc(int& id){ if(arr.size()==10) return; if(!id) id = obov(); myfunc(arr[id]); cout << arr[id] << '\n'; } int main(){ int a = obov(); myfunc(a); cout << a << '\n'; return 0; } ( https://pastebin.com/upZsetu0 ) 補充說明(Supplement): 似乎改寫成 int a = arr[id]; myfunc(a); arr[id] = a; 就不會有問題了,想請各位大大幫我指出問題點QQ -- ╭─────────────────╮ │ 遠くへと広がるの色暖かく│ │ 夢の中で描いたのようなんだ│ │切なくて時をまきもどしてみるかい?│ │ No No No いまが最高!│ ╰─────────────────╯ - -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.102.192 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1521121864.A.B51.html ※ 編輯: oToToT (123.193.102.192), 03/15/2018 21:54:07
edisonhello: vector在插東西的時候有可能會長大(? 03/15 22:13
edisonhello: 你可以在每個obov裡面印一下&arr[i] 然後就發現會跳 03/15 22:15
oToToT: 喔喔,因為他底層是指標類的東東QQ所以會寫到錯的地方 03/15 22:38
edisonhello: 所以才會有iterator這種東西 03/15 22:54
oToToT: 我發現我不會用iterator改寫這份code 03/15 23:35
LPH66: 你這個應該不能直接用 iterator 做, 理由類似 03/16 00:04
LPH66: 在長大的時候舊的 iterator 會失效, 所以你回頭的時候 03/16 00:05
LPH66: 依然會發生違規 03/16 00:05
LPH66: 是有個避免長大的解法叫 .reserve() 就是了... 03/16 00:07
steve1012: 你是本來就想寫遞回嗎 然後為啥要傳vector element 的 03/16 00:07
steve1012: reference 回去? 03/16 00:07
steve1012: 你可以傳 index… lol 03/16 00:07
edisonhello: 喔喔 原來iterator也會爛... (剛剛實驗過了) 03/16 00:20
edisonhello: 那iterator到底是為了什麼而出現的啊 03/16 00:20
jerryh001: 如果是list的話iterator就不會跑掉了 03/16 00:34
stucode: iterator 是為了抽象化容器的存取用的。例如實作一個找出 03/16 00:49
stucode: 容器中最大值的演算法,如果沒有 iterator 來抽象元素 03/16 00:50
stucode: 存取動作,對於像是 list 與 array 等疊代方式不同的 03/16 00:50
stucode: 容器,就需要針對每種容器各寫一份。 03/16 00:50
steve1012: iterator 本來就有可能被 invalidate 03/16 05:12
loveflames: 只有關聯容器跟list能保證iterator有效性 03/16 09:27