在构造std :: vector时如何放置元素?
我想构造一个 std :: vector
,其中某些元素具有由某些特定构造函数而不是默认构造函数构造的这些元素。换句话说,我想在构建矢量时放置元素。我该怎么做?
I want to construct an std::vector
with some elements having these elements constructed by some particular constructor rather than the default constructor. In other words I want to emplace the elements while constructing the vector. How can I do that?
考虑此:
struct Item
{
Item(double) {}
Item(const Item&) = delete;
Item(Item&&) = delete;
};
std::vector<Item> vv(10, 3.14); // Fails! Tries to copy while I want to emplace.
您的项目
类不支持复制或移动。这将防止 std :: vector
上的大多数操作编译,包括 std :: vector :: reserve
和 std :: vector :: resize
。如果确实有这样的类,则可能需要 std :: vector< std :: aligned_storage_t< sizeof(Item),alignof(Item)>>>
。
Your Item
class doesn't support copies nor moves. This will prevent most operations on std::vector
from compiling, including std::vector::reserve
and std::vector::resize
. If you really have such a class, you might want an std::vector<std::aligned_storage_t<sizeof(Item), alignof(Item)>>
instead.
如果可以将移动构造函数添加到 Item
,则可以创建辅助函数,而不是(as您正在使用的构造函数重载是根据复制定义的)。请注意,以下版本仅适用于一元构造函数。
If you can add a move constructor to Item
, you can create your helper function instead (as the constructor overload that you're using is defined in terms of copying). Note that the version below only works for unary constructors.
template <typename T, typename Arg>
auto make_vector(std::size_t n, Arg&& arg)
{
std::vector<T> result;
result.reserve(n);
for(std::size_t i = 0; i < n; ++i)
result.emplace_back(arg);
return result;
}
用法:
auto vec = make_vector<Item>(10, 3.14);