[問題] STL container (vector, list)/ 記憶體 …
(問題已解決)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Linux
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
CPLEX
但是目前不是問題關鍵
問題(Question):
我想用 vector<vector<T> >
或是 list<list<T> >
建立一個二維的結構 (因為會常常從中間刪減或增加 目前考慮用 list 但亦非重點)
我在一個 function BuildCBank() 中初始建立這個結構
用 push_back 這個 function 把 local 的 object (屬於 class T) 加入
因為我看網站上寫
void push_back ( const T& x );
The content of this new element is initialized to a copy of x
但是一跳出這個 BuildCBank()
二維結構內容好像就變垃圾了?為什麼呢?
請問該怎麼改?
(ans: 把黃色部分刪掉)
程式碼(Code):(請善用置底文網頁, 記得排版)
底下以 T 是 int 為例
class SA{
.....
vector<vector<int> > *ConstraintBank;
};
void SA::BuildCBank()
{
bool verbose = 0;
vector<vector<int> > *ConstraintBank = new vector<vector<int> > ();
//黃色部分刪掉就對了
//ConstraintBank should be deleted in destructor
for(int i=0;i<someConstant;i++){
vector<int> tempList;
for(int j=0;j<size;j++){ //長度size 也不重要
int *tempExpr = new int(1);
....//設定tempExpr
tempList.push_back(*tempExpr);
delete tempExpr;
}
ConstraintBank->push_back(tempList);
}
cout<<"setting done.\n";
cout<<"size is:"<<(*ConstraintBank)[0].size()<<endl; //會印出 size ok
(*ConstraintBank)[0][0] = 4; //隨便改一下
cout<<"inside test"<<endl;
cout<<(*ConstraintBank)[0][0]<<endl; //印出4 ok
}
void SA::SomeOtherFunction()
{
BuildCBank();
cout<<"outside test"<<endl;
cout<<"size is:"<<(*ConstraintBank).size()<<endl; //記憶體區段錯誤
cout<<(*ConstraintBank)[0][0]<<endl;
}
請幫忙找錯或是指正我觀念不對的地方吧
另外若 T 改成 user-defined 的 class 還需要注意什麼嗎
(我知道要有 copy ctor)
麻煩了 感謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.36.229.198
※ 編輯: jackwei 來自: 114.36.229.198 (08/19 09:16)
※ 編輯: jackwei 來自: 114.36.229.198 (08/19 09:18)
→
08/19 09:46, , 1F
08/19 09:46, 1F
推
08/19 10:10, , 2F
08/19 10:10, 2F
→
08/19 10:17, , 3F
08/19 10:17, 3F
推
08/19 10:33, , 4F
08/19 10:33, 4F
→
08/19 10:45, , 5F
08/19 10:45, 5F
→
08/19 10:56, , 6F
08/19 10:56, 6F
→
08/19 10:59, , 7F
08/19 10:59, 7F
→
08/19 13:05, , 8F
08/19 13:05, 8F
※ 編輯: jackwei 來自: 114.36.228.203 (08/19 13:06)
※ 編輯: jackwei 來自: 114.36.228.203 (08/19 13:07)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章