【问题标题】:c++ unordered map emplace Invalid argumentsc++ unordered_map emplace 无效参数
【发布时间】:2016-09-02 14:24:24
【问题描述】:

如果我有这张地图

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

我怎么能这样:

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

但我不能这样做:

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

无效参数' 候选人是: ?就位(#10000(...)&& ...) ' 我不明白为什么会这样。感谢您的帮助。

【问题讨论】:

  • 尝试sockets.emplace(std::make_pair (_myId,(int*)lp))
  • @vadikrobot emplace 在这种情况下将采用 2 个参数 - 键和值。您正在考虑插入。
  • 无法复制,适合我。 std::unordered_map&lt;std::string, int*&gt; sockets; bool foo(const char *p, int n) { return sockets.emplace(p, &amp;n).second; }
  • 也适合我godbolt.org/g/C5jZUm
  • .. 可怕的想法,c 样式转换为 c 样式指针(数组?)你不能使用套接字句柄的向量吗?

标签: c++ unordered-map emplace


【解决方案1】:

那有什么更好的写法呢?

这是一个无序映射,将某个标识符映射到多个套接字。

在 BSD 套接字中,套接字描述符是一个 int(或至少可转换为一个),所以让我们继续使用它。

似乎每个标识符关联的套接字不止一个。这证明了一个向量。

所以:

using socket_vector = std::vector<int>;

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

现在我们可以将套接字附加到每个标识:

sockets[ident].push_back(sock);

【讨论】:

    【解决方案2】:
    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));
    

    【讨论】:

      猜你喜欢
      • 2014-12-14
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 2013-12-06
      相关资源
      最近更新 更多