use*_*118 1 c++ pointers stdmap stdvector
我想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;
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
如何将新tmp插入向量?
信息如下:
Paris,Juli,5,3,6
Paris,John,24,2
Canberra,John,4,3
London,Mary,29,4,1,2
Run Code Online (Sandbox Code Playgroud)
这里有很多错误,它们都源于滥用指针.作为问题原因提到的那一行是一个轻微的句法问题.手头有更大的问题.
所有这些都可以通过不滥用指针轻松解决.没有理由在这里使用指针,所以最终的解决方法是让地图具有这种类型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
Run Code Online (Sandbox Code Playgroud)
现在我们有一个简单的解决方案,我会在房间代码中提到大象.
vector<info>* ss = new vector<info>;
ss=&(tp);
// ...
log.insert(map<string,vector<info> * >::value_type(city,ss));
Run Code Online (Sandbox Code Playgroud)
这一系列操作将创建一个具有动态存储持续时间的向量,并立即丢弃指向它的唯一指针.这导致刚刚创建的向量丢失,并且它使用的内存被泄露; 它再也无法恢复了.
更糟糕的是,它设置ss
为指向局部变量,然后将该指针保存到地图中的局部变量.因为局部变量具有自动存储持续时间,所以一旦函数返回它就会消失.这使得刚存储在地图中的指针无效,因为它不再有指向的向量.在那之后,各种各样的破坏将被打破.