2012-10-17 137 views
1

我想用一個指針我有下面的示例代碼中插入新元素放入vector如何通過指針訪問矢量?

struct info { 
    string Name; 
    int places; // i will use the binary value to identfy the visited places example 29 is 100101 
       // this means he visited three places (London,LA,Rome) 
    vector<int> times; // will represent the visiting time,e.g. 1,2,5 means london 1 time, LA 
         // twice and Rome five times 
}; 

map<string,vector<info> *> log; 

Peaple是從不同的城市來了,我會如果城市存在的檢查,只是新的人加入到vector,否則創造一個新的地圖對象:

vector<info> tp; 
info tmp; 
if(log.size()==0|| log.count(city)==0) //empty or not exist 
{ 
    tp.push_back(tmp); 
    vector<info>* ss = new vector<info>; 
    ss=&(tp); 
    // create a new object 
    log.insert(map<string,vector<info> * >::value_type(city,ss)); // new object 
} 
else // city exist, just add the information to the vector 
{ 
    map<string,vector<info> *>::iterator t; 
    t=log.find(city); 
    *(t->second).push_back(tmp); //the problem in this line 
} 

我怎樣才能將新的TMP到載體?

的信息進行讀取,如下所示:

Paris,Juli,5,3,6 
Paris,John,24,2 
Canberra,John,4,3 
London,Mary,29,4,1,2 
+0

你提到的問題是在某一行,但從來沒有解釋是什麼問題。它是什麼? –

+4

刪除你程序中的所有星號,然後修改它來編譯。你會好很多。 – avakar

+0

你是否建議他停止使用指針?請解釋... – mtsvetkov

回答

5

這裏有很多的失誤,他們都從濫用指針幹。所提到的這個問題的原因是一個小的語法問題。手頭有更大的問題。

所有這些都可以通過不誤用指針來解決。沒有理由在這裏使用指針,所以最終的解決方法是使地圖具有這種類型map<string,vector<info>> log;

然後代碼變成是這樣的:

info tmp; 
log[city].push_back(tmp); 
// the [] operator creates a new empty vector if it doesn't exist yet 
// there's no point in doing the checks by hand 

現在,我們有一個簡單的解決方案,我會提到在 代碼的大象。

vector<info>* ss = new vector<info>; 
ss=&(tp); 
// ... 
log.insert(map<string,vector<info> * >::value_type(city,ss)); 

該操作序列將創建動態存儲持續時間的矢量,並立即唯一指針丟棄它。這會導致剛創建的向量丟失,並且它使用的內存被泄漏;它不能恢復。

更糟糕的是,它將ss設置爲指向局部變量,然後將該指針保存到地圖中的局部變量。因爲局部變量具有自動存儲持續時間,所以一旦函數返回,它就會消失。這使得存儲在地圖中的指針無效,因爲它不再有指向的矢量。之後,各種浩劫就會發生。

+0

似乎你不需要'if':你在'log [city] .push_back(tmp);'做這兩種情況。 –

+1

@ Mr.C64哦,你說得對。我認爲我已經使代碼已經非常簡單了) –

+0

謝謝,這使得這麼簡單 我需要打印日誌的內容我寫了 'vector :: iterator j;對於(i = log.begin(); i!= log.end(); i ++) {cout <<「From」<< i-> first <<「city people who travels:」<< endl; for for(size_t tt = 0; tt < (i-> second).size(); tt ++) { cout << (i-> second [tt])。名稱<<「去了」<< (i->秒)[tt] .places <<「\ n帶有下面的訪問時間」;對於(j =((i-> second [tt])次).begin(); j!=((i-> second [tt]).times).end(); j ++)cout << * j <<「」; }}' – user1749118

0

看起來你需要做這樣的

(t->second)->push_back(tmp); 
+0

不工作我得到了同樣的錯誤消息(('push_back'尚未聲明)) – user1749118

+0

它應該是'(* t-> second) - > push_back(tmp);'。 – avakar