Crusader370
Crusader370

Reputation: 25

C++ call a member function of an anonymous object instance?

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.

Upvotes: 0

Views: 154

Answers (3)

armagedescu
armagedescu

Reputation: 2158

Not tested but try something like this:

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

Ok, let's sumarize. There is an important thing to know about insert: the insert doesn't insert if key already exists.

//create and initialise inline a map with int keys and string values
map<int, string> x {
                     {10,  "hello"},
                     {123, "bye"},
                     {234, "world"}
                   };
x.insert({567, "alien"}); //inserts an element initialised inline
x.insert({567, "bar"});   //does nothing, according to specs
x[124] = "buzz"; //inserts an element
x[567] = "bar";  //modifies the element with key 567

//create and initialise inline a map with int keys and int values
map<int, string> y {
                     {10,  1},
                     {123, 2},
                     {234, 3}
                   };
y.insert({567, 4}); //insert  an element initialised inline
z[124] = 5; //inserts
z[124] = 6; //modifies the above element
z[125]++;   //inserts and modifies, now z[125] is 1
z[125]++;   //modifies the above element to 2

It is very flexible. If you create a map of containers

//create  and initialise inline a map with int keys and set values
map<int, set<int>> x {
                     {10,  {1, 2, 3}},
                     {123, {2, 3}},
                     {234, {1, 2, 3}}}
                   };
//calling insert on map:
y.insert({567, {4, 5, 6}}); //element 567 has the value {4, 5, 6}
//now this calls insert in the set:
y[567].insert(7); //element 567 exists, so it is modified to {4, 5, 6, 7}
y[568].insert(7); //element 569 doesn't exist, so it is created first
//assign
y[235] = {4, 5, 6}; //element 235 has the value {4, 5, 6}
y[235] = {7, 8, 9}; //element 235 has the value {7, 8, 9}
y[235].insert(10);  //element 235 has the value {7, 8, 9, 10}

Upvotes: 3

Remy Lebeau
Remy Lebeau

Reputation: 596256

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);

Upvotes: 1

Klaus
Klaus

Reputation: 25613

You need none of your intermediate steps!

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

Upvotes: 2

Related Questions