如何插入集合
How do I insert into a set?
我知道显而易见的方法是使用插入功能。我正在尝试做的是将给定的电话号码放入电话地图和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);
}
相关文章:
- 如何将结构插入到集合中并打印集合的成员
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 将基元类型插入到集合中
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 如何将值插入到 c++ boost::multiindex 集合的特定索引中,就像在 std::list 中一样
- 为什么以相同的数量插入到集合中,基于不同的方法具有不同的运行时间?
- 将地址插入到集合中,集合的大小小于预期
- 我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?
- 如何插入集合
- 如何在C++的集合中插入一系列元素
- 如何在集合中插入字符
- 将集合插入/读取到地图中
- 方法插入到任何stl集合中
- C - 如何将自己类型的值插入集合中
- 如何将数组插入无序集合
- 集合的复杂性::插入
- 将配对插入集合时编译错误
- 集合未插入
- 自定义比较器,将唯一元素插入到c++中的集合中
- 如何将对象插入到集合中