我可以将一个值放置到存储在C++映射中的向量中吗



我想知道是否可以将值放置到存储在映射中的向量中。

目前我这样做…

std::map<std::string, std::vector<std::string>> my_collection;
my_collection["Key"].push_back("MyValue");

我在想我可以做以下事情,C++会足够聪明,意识到它应该把它添加到向量中。。。但是我遇到了一个内存编译错误。

my_collection.emplace("Key", "MyValue");

您可以创建一个向量,将其放置在其中,然后移动向量。这样你的对象既不会被复制也不会被移动:

std::map<std::string, std::vector<std::string>> my_collection;
std::vector<std::string> temp;
temp.emplace_back("MyValue");
my_collection["Key"] = std::move(temp);

或者,您可以在地图中创建矢量,并使用参考:

std::map<std::string, std::vector<std::string>> my_collection;
auto &keyVec = my_collection["Key"];
keyVec.emplace_back("MyValue");

方便地说,这可以归结为:

std::map<std::string, std::vector<std::string>> my_collection;
my_collection["Key"].emplace_back("MyValue");

无论smartC++如何发展,它仍然必须尊重语言规则和公共接口。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));
}

最新更新