Home > Back-end >  C call a member function of an anonymous object instance?
C call a member function of an anonymous object instance?

Time:11-28

I have the following piece of code:

map<int, set<int>> my_map;
int my_int1, my_int2;
// some code
set<int> temp;
temp.insert(my_int2);
my_map.insert(make_pair(my_int1, temp));

Is there some way to avoid using the temp (at least just for the code to look nicer, not necessarily for performance) and use an anonymous object? Something like:

my_map.insert(make_pair(my_int1, (set<int>{}).insert(my_int2)));

Except, the above line doesn't compile.

CodePudding user response:

Not tested but try something like this:

my_map.insert({my_int1, {my_int2}});

CodePudding user response:

You need none of your intermediate steps!

int main()
{
    std::map<int, std::set<int>> my_map;
    my_map.insert({1,{}});
}

CodePudding user response:

You don't need the temporary std::set at all. Simply use std::map::operator[] to create the std::set in the std::map if it doesn't already exist, and then you can insert() into that std::set directly, eg:

map<int, set<int>> my_map;
int my_int1, my_int2;
// some code
my_map[my_int1].insert(my_int2);
  •  Tags:  
  • c
  • Related