12

我可以为 map::emplace 找到的所有示例都使用相当简单的类型,这些类型的构造函数采用单个参数,例如

std::map<std::string, std::string> foo;
foo.emplace("a", "b");

假设值类型构造函数需要两个参数。哎呀,让我们真的让它变得简单;假设值类型是std::pair<std::string, double>. 如何使用std::map<string, pair<string, double> >::emplace()在地图中就地构造值类型?

我知道这不起作用:

std::map<std::string, std::pair<std::string, double> > foo;
foo.emplace("a", "b", 1.0);

至少,它在 g++ 4.8.2 上大声而冗长地失败了。这甚至可以用 C++11 实现吗?

4

1 回答 1

13

我的搜索能力很弱。这实际上在另一个 stackoverflow question中得到了很好的和启发性的详细回答。

简短的回答:

foo.emplace(std::piecewise_construct,
            std::forward_as_tuple("a"),
            std::forward_as_tuple("b", 1.0));
于 2015-04-30T22:16:16.877 回答