无论 C++ 变得如何智能,它仍然必须尊重语言规则和公共接口。 std::map 确实有一个 emplace 成员。你需要使用它。
问题是没有办法通过将元素移动到向量中来构造向量(因为 std::initializer_list 的设计方式 - 不要让我开始)
如果您不关心这一点并且可以接受将元素复制到向量中,那么您需要做的就是:
auto test()
{
using namespace std::string_literals;
std::map<std::string, std::vector<std::string>> my_collection;
my_collection.emplace("key"s, std::vector{"MyValue"s});
}
上面会将"MyValue"s复制到一个向量中,然后将键和向量移动到地图中。
但是,如果您确实想要移动或只有移动类型,那么还有一些额外的工作。
所以我创建了一个小实用函数:通过移动传递给它的右值来创建一个向量:
template <class... Args>
auto make_vector(Args&&... args)
{
using T = std::remove_reference_t<std::common_type_t<Args...>>;
static_assert((... && std::is_same_v<T, std::remove_reference_t<Args>>));
auto v = std::vector<T>{};
v.reserve(sizeof...(Args));
(..., v.emplace_back(std::forward<Args>(args)));
return v;
}
auto test()
{
using namespace std::string_literals;
std::map<std::string, std::vector<std::string>> my_collection;
my_collection.emplace("key", make_vector("MyValue"s));
}