我知道显而易见的方法是使用插入功能。我正在尝试做的是将给定的电话号码放入电话地图和phone_numbers集中。它可以将其放入地图中,但是当它到达phone_numbers设置时,它会出错。Add_Phone函数和电话映射位于一个名为 Code_Processor 的类中
class User {
public:
string username;
string realname;
int points;
set <string> phone_numbers;
};
map <string, User *> Phones;
int Code_Processor::Add_Phone(string username, string phone) {
//register the given phone # with given user
//put the phone on both Phones map and phone_numbers set
//use .insert()
User *nUser = new User;
map <string, User *>::iterator nit;
nit = Phones.find(username);
Phones.insert(make_pair(username, nUser)); //put into Phones map
nit->second->phone_numbers.insert(phone); //this is where is seg faults!!
return 0;
}
您在
插入到映射之前搜索username
,如果用户不存在,则nit
将是不应取消引用的end
迭代器。如果你取消引用它(就像你所做的那样(,那么你将有未定义的行为。
相反,要解决您的问题,请依赖于以下事实:insert
函数将迭代器返回到插入的元素。
然后你可以做一些类似的事情
auto inserted_pair = Phones.insert(make_pair(username, nUser));
if (inserted_pair.first != Phones.end())
{
inserted_pair.first->phone_numbers.insert(phone);
}