std::inplace_vector<T,N>:: assign
From cppreference.net
<
cpp
|
container
|
inplace vector
|
constexpr
void
assign
(
size_type count,
const
T
&
value
)
;
|
(1) | (自 C++26 起) |
|
template
<
class
InputIt
>
constexpr void assign ( InputIt first, InputIt last ) ; |
(2) | (自 C++26 起) |
|
constexpr
void
assign
(
std::
initializer_list
<
T
>
ilist
)
;
|
(3) | (自 C++26 起) |
替换容器中的内容。
1)
将内容替换为
count
份
value
值的副本。
2)
将内容替换为范围
[
first
,
last
)
中元素的副本。
如果
first
或
last
是指向
*
this
的迭代器,则行为未定义。
3)
将内容替换为来自
ilist
的元素。
| 本节内容尚不完整 |
目录 |
参数
| count | - | 容器的新大小 |
| value | - | 用于初始化容器元素的值 |
| first, last | - | 定义待复制元素源 范围 的迭代器对 |
| ilist | - | 复制值来源的 std::initializer_list |
复杂度
1)
与
count
呈线性关系。
2)
与
first
和
last
之间的距离成线性关系。
3)
与
ilist.
size
(
)
呈线性关系。
异常处理
1-3)
由插入元素的初始化抛出的任何异常。
示例
以下代码使用
assign
向
std::
inplace_vector
<
char
,
5
>
添加若干字符:
运行此代码
#include <inplace_vector> #include <iterator> #include <new> #include <print> int main() { std::inplace_vector<char, 5> chars; chars.assign(4, 'a'); // 重载 (1) std::println("{}", chars); const char extra[3]{'a', 'b', 'c'}; chars.assign(std::cbegin(extra), std::cend(extra)); // 重载 (2) std::println("{}", chars); chars.assign({'C', '+', '+', '2', '6'}); // 重载 (3) std::println("{}", chars); try { chars.assign(8, 'x'); // 抛出异常:count > chars.capacity() } catch(const std::bad_alloc&) { std::println("std::bad_alloc #1"); } try { const char bad[8]{'?'}; // ranges::distance(bad) > chars.capacity() chars.assign(std::cbegin(bad), std::cend(bad)); // 抛出异常 } catch(const std::bad_alloc&) { std::println("std::bad_alloc #2"); } try { const auto l = {'1', '2', '3', '4', '5', '6'}; chars.assign(l); // 抛出异常:l.size() > chars.capacity() } catch(const std::bad_alloc&) { std::println("std::bad_alloc #3"); } }
输出:
['a', 'a', 'a', 'a'] ['a', 'b', 'c'] ['C', '+', '+', '2', '6'] std::bad_alloc #1 std::bad_alloc #2 std::bad_alloc #3
参见
|
为容器赋值一个值范围
(公开成员函数) |
|
|
为容器赋值
(公开成员函数) |