如何通过指针访问向量?

时间:2012-10-17 08:23:21

标签: c++ pointers stdvector stdmap

我想使用指针将新元素插入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

2 个答案:

答案 0 :(得分: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

现在我们有一个简单的解决方案,我会在 room 代码中提到大象。

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

这一系列操作将创建一个具有动态存储持续时间的向量,并立即丢弃指向它的唯一指针。这导致刚刚创建的向量丢失,并且它使用的内存被泄露;它再也无法恢复了。

更糟糕的是,它将ss设置为指向局部变量,然后将该指针保存到地图中的局部变量。因为局部变量具有自动存储持续时间,所以一旦函数返回它就会消失。这使得刚存储在地图中的指针无效,因为它不再有指向的向量。在那之后,各种各样的破坏都会被破坏。

答案 1 :(得分:0)

看起来你需要这样做

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