Skip to main content

std::string push_back() method

constexpr void push_back( CharT ch );

Appends the given character ch to the end of the string.

Parameters

  • ch - the character to append

Return value

(none)

Complexity

Amortized constant - O(1).

Exceptions

If the operation would result in size() > max_size(), throws std::length_error.

In any case, if an exception is thrown for any reason, this function has no effect (strong exception guarantee).  (since C++11)

Example

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);
}
Output
before="Short string"
after="Short string!"
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::string push_back() method

constexpr void push_back( CharT ch );

Appends the given character ch to the end of the string.

Parameters

  • ch - the character to append

Return value

(none)

Complexity

Amortized constant - O(1).

Exceptions

If the operation would result in size() > max_size(), throws std::length_error.

In any case, if an exception is thrown for any reason, this function has no effect (strong exception guarantee).  (since C++11)

Example

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);
}
Output
before="Short string"
after="Short string!"
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.