[問題] 問一個可能算基本的STL使用...

看板C_and_CPP作者 (....)時間7年前 (2017/01/05 18:18), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Win8 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) VC2008 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) STL 問題(Question): 我想問為什麼以下的程式碼跑起來在建立obj2時會有錯誤... #include <iostream> #include <vector> #include <algorithm> using namespace std; void println(const vector<int>& that) { for (int i=0; i<that.size(); i++) { cout<< that[i]<<","; } cout<<endl; } class A { public: A(); vector<int> Value; }; class B { public: vector<int> Value; B(const A&); }; A::A() { } B::B(const A& inn) { std::copy(inn.Value.begin(), inn.Value.end(), Value.begin()); } int main() { A obj1; obj1.Value.push_back(1); obj1.Value.push_back(2); obj1.Value.push_back(3); println(obj1.Value); B obj2(obj1); //這裡會跳Debug Assertion Fail... println(obj2.Value); return 0; } 餵入的資料(Input): none... 預期的正確結果(Expected Output): none... 錯誤結果(Wrong Output): "Debug Assertion Fail" 程式碼(Code):(請善用置底文網頁, 記得排版) 已經貼了.. 補充說明(Supplement): -- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.254.8.178 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1483611503.A.090.html

01/05 18:37, , 1F
你要先Value.resize(inn.Value.size()) 再copy
01/05 18:37, 1F

01/05 18:38, , 2F
或是直接B(const A& inn):Value(inn.Value){}
01/05 18:38, 2F

01/05 19:27, , 3F
std::copy()不會幫你申請空間 只有複製行為
01/05 19:27, 3F
文章代碼(AID): #1ORXrl2G (C_and_CPP)