作者jackwei (吐司)
看板C_and_CPP
標題[問題] STL container (vector, list)/ 記憶體 (new) 的問題
時間Fri Aug 19 09:16:11 2011
(問題已解決)
開發平台(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)
→ angleevil:~"~你應該是宣告一個object來用吧! 08/19 09:46
推 kasase:BuildCBank()裡不用再宣告一個vector<vector<T> > * 08/19 10:10
→ jackwei:沒有new 怎麼拿到空間呢? 08/19 10:17
推 littleshan:同二樓 08/19 10:33
→ jackwei:orz 我腦殘加眼殘 08/19 10:45
→ angleevil:我好奇的是main裡面的BuildCBank可以直接用嘛? 08/19 10:56
→ angleevil:int main<--你是不是要表達是member function阿 08/19 10:59
→ jackwei:喔那樣的確不能直接用 sorry key太快 08/19 13:05
※ 編輯: jackwei 來自: 114.36.228.203 (08/19 13:06)
※ 編輯: jackwei 來自: 114.36.228.203 (08/19 13:07)