Home > database >  std::map<int, std::set*>> here my_map[1] = std::set<int*>(); ---> what does this l
std::map<int, std::set*>> here my_map[1] = std::set<int*>(); ---> what does this l

Time:04-29

Below is my code, wanted to know what does the line my_map[1] = std::set<int*>(); serve?

std::map<int, std::set<int *>> my_map;

int main() {
  int i = 10;
  int *ptr = &i;
  my_map[1] = std::set<int *>();
  my_map[1].insert(ptr);
  for (std::map<int, std::set<int *>>::const_iterator it = my_map.begin();
       it != my_map.end(); it  ) {
    cout << it->first << "-->";
    for (std::set<int *>::const_iterator itt = it->second.begin();
         itt != it->second.end(); itt  ) {
      cout << *(*itt) << "\t";
    }
    cout << endl;
  }
  cout << "Hello World";

  return 0;
}

CodePudding user response:

As said it creates an empty set and assigns it to my_map[1].

However, it's not needed. If no element exists for a key, then accessing that key with [] will create a default-constructed data-element.

This code:

    int i = 10;
    my_map[1].insert(&i);

is enough.

CodePudding user response:

It create a new empty entry in 'my_map' with key '1', and then return the reference of value related to this entry. And then call the 'std::set<int*>::operator=' method to copy the left one set which created by std::set<int *>() to this reference.

  • Related