跳到主要内容

std::string push_back() 方法

constexpr void push_back( CharT ch );

将给定字符 ch 附加到字符串的末尾。

参数

  • ch - 要附加的字符

返回值

(无)

复杂度

分摊常数 - O(1)

异常

如果操作导致 size() > max_size(),则抛出std::length_error

在任何情况下,如果由于任何原因抛出异常,此函数无效(强异常保证)。 (自 C++11 起)

示例

Main.cpp
#include <cassert>
#include <string>
#include <iomanip>
#include <iostream>

int main()
{
std::string str{"Short string"};
std::cout << "before=" << std::quoted(str) << '\n';
assert(str.size() == 12);

str.push_back('!');
std::cout << " after=" << quoted(str) << '\n';
assert(str.size() == 13);
}
输出
before="Short string"
after="Short string!"
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而有所修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string push_back() 方法

constexpr void push_back( CharT ch );

将给定字符 ch 附加到字符串的末尾。

参数

  • ch - 要附加的字符

返回值

(无)

复杂度

分摊常数 - O(1)

异常

如果操作导致 size() > max_size(),则抛出std::length_error

在任何情况下,如果由于任何原因抛出异常,此函数无效(强异常保证)。 (自 C++11 起)

示例

Main.cpp
#include <cassert>
#include <string>
#include <iomanip>
#include <iostream>

int main()
{
std::string str{"Short string"};
std::cout << "before=" << std::quoted(str) << '\n';
assert(str.size() == 12);

str.push_back('!');
std::cout << " after=" << quoted(str) << '\n';
assert(str.size() == 13);
}
输出
before="Short string"
after="Short string!"
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而有所修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。