【问题标题】:Inserting std::tuple into the std::map将 std::tuple 插入 std::map
【发布时间】:2019-08-19 10:20:33
【问题描述】:

以下示例代码无法编译,我无法弄清楚如何将 inttuple 插入到地图中。

#include <tuple>
#include <string>
#include <map>

int main()
{
    std::map<int, std::tuple<std::wstring, float, float>> map;
    std::wstring temp = L"sample";

    // ERROR: no instance of overloaded function matches the argument list
    map.insert(1, std::make_tuple(temp, 0.f, 0.f));

    return 0;
}

将示例int, std::tuple 插入地图的正确方法是什么

【问题讨论】:

  • 如果你的值类型是int,你会得到同样的错误。你认为这应该叫什么overload of insert

标签: c++ dictionary insert tuples


【解决方案1】:

随便

map.insert(std::make_pair(1, std::make_tuple(temp, 0.f, 0.f)));

map.emplace(1, std::make_tuple(temp, 0.f, 0.f));

这实际上更好,因为它创造的临时性更少。

编辑:

甚至有可能根本不创建临时对象:

map.emplace(std::piecewise_construct, std::forward_as_tuple(1),
    std::forward_as_tuple(temp, 0.f, 0.f));

【讨论】:

  • 不知何故忘记了 std::make_pair 并从您的回答中学到了新东西!
  • @zebanovich - std::piecewise_construct 的可能性是我在过去几天中学到的。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2010-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多