std::basic_string<CharT,Traits,Allocator>::resize
来自cppreference.com
<tbody>
</tbody>
void resize( size_type count ); |
(1) | (C++20 起为 constexpr) |
void resize( size_type count, CharT ch ); |
(2) | (C++20 起为 constexpr) |
重设字符串大小,使其包含 count 个字符。
如果当前大小小于 count,那么后附额外的字符:
1) 将后附的字符初始化为
CharT()(在 CharT 是 char 时就是 '\0')。2) 将后附的字符初始化为
ch。如果当前大小大于 count,那么字符串会缩减到首 count 个元素。
参数
| count | - | 字符串的新大小 |
| ch | - | 用以初始化新字符的字符 |
异常
在 count > max_size() 是 true 时抛出 std::length_error。也会抛出对应 Allocator 所抛的任何异常。
如果因为任何原因抛出了异常,那么此函数无效果(强异常安全保证)。
示例
运行此代码
#include <iomanip>
#include <iostream>
#include <stdexcept>
int main()
{
const unsigned desired_length{8};
std::string long_string("Where is the end?");
std::string short_string("H");
std::cout << "基础功能:\n"
<< "缩短:\n"
<< "1. resize 前:" << quoted(long_string) << '\n';
long_string.resize(desired_length);
std::cout << "2. resize 后:" << quoted(long_string) << '\n';
std::cout << "以给定字符 'a' 加长:\n"
<< "3. resize 前:" << quoted(short_string) << '\n';
short_string.resize(desired_length, 'a');
std::cout << "4. resize 后:" << quoted(short_string) << '\n';
std::cout << "以 char() == " << static_cast<int>(char()) << " 加长:\n"
<< "5. resize 前:" << quoted(short_string) << '\n';
short_string.resize(desired_length + 3);
std::cout << "6. resize 后:\"";
for (char c : short_string)
std::cout << (c == char() ? '@' : c);
std::cout << "\"\n\n";
std::cout << "错误:\n";
std::string s;
try
{
// 大小 OK,没有 length_error(可能会抛出 bad_alloc)
s.resize(s.max_size() - 1, 'x');
}
catch (const std::bad_alloc& ex)
{
std::cout << "1. 异常:" << ex.what() << '\n';
}
try
{
// 大小 OK,没有 length_error(可能会抛出 bad_alloc)
s.resize(s.max_size(), 'x');
}
catch (const std::bad_alloc& ex)
{
std::cout << "3. 异常:" << ex.what() << '\n';
}
try
{
// 大小错误,抛出 length_error
s.resize(s.max_size() + 1, 'x');
}
catch (const std::length_error& ex)
{
std::cout << "3. length_error:" << ex.what() << '\n';
}
}
可能的输出:
基础功能:
缩短:
1. resize 前:"Where is the end?"
2. resize 后:"Where is"
以给定字符 'a' 加长:
3. resize 前:"H"
4. resize 后:"Haaaaaaa"
以 char() == 0 加长:
5. resize 前:"Haaaaaaa"
6. resize 后:"Haaaaaaa@@@"
错误:
1. 异常:std::bad_alloc
2. 异常:std::bad_alloc
3. length_error:basic_string::_M_replace_aux
复杂度
与字符串大小成线性。
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 847 | C++98 | 没有异常安全保证 | 添加强异常安全保证 |
| LWG 2250 | C++98 | count > max_size() 是 true 时的行为未定义
|
此时始终会抛出异常 |
参阅
| 返回字符数 (公开成员函数) | |
| 预留存储 (公开成员函数) | |
| 通过释放不使用内存减少内存使用 (公开成员函数) |