2012-10-17 93 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