【问题标题】:emplace into `std::unordered_map` with `std::pair` value [duplicate]使用 `std::pair` 值置入`std::unordered_map` [重复]
【发布时间】:2016-03-11 21:35:57
【问题描述】:

我正在尝试将值放入 std::unordered 映射中,如下所示:

std::unordered_map<std::string, std::pair<std::string, std::string>> testmap;
testmap.emplace("a", "b", "c"));

这不起作用,原因是:

错误 C2661: 'std::pair::pair' : 没有重载函数需要 3 个参数

我查看了this answerthis answer,似乎我需要将std::piecewise_construct 合并到炮位中才能使其工作,但我想我不太清楚该把它放在哪里这个案例。尝试类似

testmap.emplace(std::piecewise_construct, "a", std::piecewise_construct, "b", "c"); // fails
testmap.emplace(std::piecewise_construct, "a", "b", "c"); // fails
testmap.emplace(std::piecewise_construct, "a", std::pair<std::string, std::string>( std::piecewise_construct, "b", "c")); // fails

有什么方法可以将这些值传递给emplace

我正在使用 msvc2013 进行编译,以防万一。

【问题讨论】:

    标签: c++ c++11 unordered-map std-pair


    【解决方案1】:

    您需要使用std::piecewise_constructstd::forward_as_tuple 作为参数。

    以下编译:

    #include <unordered_map>
    
    int main()
    {
        std::unordered_map<std::string,std::pair<std::string,std::string>> testmap;
        testmap.emplace(std::piecewise_construct,std::forward_as_tuple("a"),std::forward_as_tuple("b","c"));
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2013-08-18
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多