简体   繁体   中英

How do I insert into a set?

I know the obvious way is to use the insert function. What I am trying to do is place the phone number given into the Phones map and into the phone_numbers set. It can place it into the map, but when it gets to the phone_numbers set it seg faults. The Add_Phone function and the Phone map are inside a class called 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;
}

You search for username before you insert into the map, and if the user doesn't exist then nit will be the end iterator which should not be dereferenced. If you dereference it (like you do) then you will have undefined behavior .

Instead, to solve your problem, rely on the fact that the insert functions returns the iterator to the inserted element.

Then you can do something like

auto inserted_pair = Phones.insert(make_pair(username, nUser));
if (inserted_pair.first != Phones.end())
{
    inserted_pair.first->phone_numbers.insert(phone);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM