簡體   English   中英

如何插入集合?

[英]How do I insert into a set?

我知道明顯的方法是使用插入功能。 我想做的是將給定的電話號碼放入“電話”映射和phone_numbers集中。 可以將其放置在地圖中,但是當設置到phone_numbers時,它將出現段故障。 Add_Phone函數和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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM