1

if I have this map

std::unordered_map<std::string, int*> sockets; //a map holding all active sockets 

how come I can do this :

sockets[_myId]=(int*)lp; //all ok - insert succeeds 

but I can't do this :

if(!sockets.emplace(_myId,(int*)lp).second) { /*insert failed, act accordingly*/ } 

Invalid arguments ' Candidates are: ? emplace(#10000(...) && ...) ' I don't understand why this happens. Thx for any assistance.

10
  • Try to sockets.emplace(std::make_pair (_myId,(int*)lp)) Commented Sep 2, 2016 at 14:33
  • @vadikrobot emplace in this case will take 2 arguments - key and value. you're thinking of insert. Commented Sep 2, 2016 at 14:34
  • 1
    Cannot reproduce, works for me. std::unordered_map<std::string, int*> sockets; bool foo(const char *p, int n) { return sockets.emplace(p, &n).second; } Commented Sep 2, 2016 at 14:35
  • works for me too godbolt.org/g/C5jZUm Commented Sep 2, 2016 at 14:36
  • 1
    ..horrible idea though, c-style casts to a c-style pointer (array?) can't you use a vector of socket handles? Commented Sep 2, 2016 at 14:37

2 Answers 2

1

What's a better way to write it then?

This is an unordered map mapping some identifier with a number of sockets.

In BSD sockets, a socket descriptor is an int (or at least convertible to one) so lets stay with that.

It seems that there are more than one socket associated with each identifier. This argues for a vector.

so:

using socket_vector = std::vector<int>; 

and

using ident_to_sockets = std::unordered_map<std::string, socket_vector>; 

now we can append sockets to each ident:

sockets[ident].push_back(sock); 
Sign up to request clarification or add additional context in comments.

Comments

1
std::unordered_map<std::string, int*> something; std::string a; int* b; something[a] = b; // with emplace: something.emplace(std::make_pair(a, b)); // also something.emplace(std::unordered_map<std::string, int*>::value_type(a, b)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.