-3

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;
}
Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 1
    It creates a new empty set `1` maps to. Given how `std::map::operator[]` works, this line is redundant. – Evg Apr 29 '22 at 06:38
  • 1
    You might want to learn about [the range `for` loop](https://en.cppreference.com/w/cpp/language/range-for), it will simplify your loops quite considerably. – Some programmer dude Apr 29 '22 at 06:43

2 Answers2

2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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.

BrooksLee
  • 91
  • 8