序列容器,例如
vector
、deque
和 list
,都具有构造函数来创建包含特定数量元素的容器。
std::向量:
//Constructs the vector with count copies of elements with value value.
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator() );
//Constructs the vector with count default-inserted instances of T. No copies are made.
explicit vector( size_type count,
const Allocator& alloc = Allocator() );
std::列表:
//Constructs the list with count copies of elements with value value.
list( size_type count,
const T& value,
const Allocator& alloc = Allocator() );
//Constructs the list with count default-inserted instances of T. No copies are made.
explicit list( size_type count,
const Allocator& alloc = Allocator() );
std::双端队列:
//Constructs the deque with count copies of elements with value value.
deque( size_type count,
const T& value,
const Allocator& alloc = Allocator() );
//Constructs the deque with count default-inserted instances of T. No copies are made.
explicit deque( size_type count,
const Allocator& alloc = Allocator() );
为什么关联容器没有这样的构造函数?
这样的构造函数实际上没有用。
如果您创建了一个元素全部相等的关联数组,它们将具有相同的键和值。 这对于简单的地图和集合来说毫无用处;对于多值版本,您仍然只能创建包含多个单键的实例,并且没有令人信服的案例将这种很少需要的功能添加到库中。
如果你真的需要它,你可以编写自己的函数。 例如:
#include <ranges>
#include <set>
template<class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key>>
auto create_multiset_containing(std::size_t count, Key const& element,
const Compare& comp = Compare{},
const Allocator& alloc = Allocator{})
{
return std::multiset<Key, Compare, Allocator>(std::from_range,
std::views::repeat(element, count),
comp, alloc);
}