Difference between revisions of "cpp/string/basic string/push back"
From cppreference.com
< cpp | string | basic string
m (→Exceptions: fmt) |
m (Add simple example) |
||
Line 28: | Line 28: | ||
If the operation would result in {{c|size() > max_size()}}, throws {{lc|std::length_error}}. | If the operation would result in {{c|size() > max_size()}}, throws {{lc|std::length_error}}. | ||
+ | |||
+ | ===Example=== | ||
+ | {{example | ||
+ | | code= | ||
+ | #include <cassert> | ||
+ | #include <string> | ||
+ | #include <iostream> | ||
+ | |||
+ | int main() | ||
+ | { | ||
+ | std::string str("Short string"); | ||
+ | std::cout << "before='" << str << "'\n"; | ||
+ | assert(str.size() == 12); | ||
+ | |||
+ | str.push_back('X'); | ||
+ | std::cout << " after='" << str << "'\n"; | ||
+ | assert(str.size() == 13); | ||
+ | } | ||
+ | | output= | ||
+ | before='Short string' | ||
+ | after='Short stringX' | ||
+ | }} | ||
===See also=== | ===See also=== |
Revision as of 14:35, 18 January 2022
void push_back( CharT ch ); |
(until C++20) | |
constexpr void push_back( CharT ch ); |
(since C++20) | |
Appends the given character ch
to the end of the string.
Contents |
Parameters
ch | - | the character to append |
Return value
(none)
Complexity
Amortized constant.
Exceptions
If an exception is thrown for any reason, this function has no effect (strong exception guarantee).(since C++11)
If the operation would result in size() > max_size(), throws std::length_error.
Example
Run this code
#include <cassert> #include <string> #include <iostream> int main() { std::string str("Short string"); std::cout << "before='" << str << "'\n"; assert(str.size() == 12); str.push_back('X'); std::cout << " after='" << str << "'\n"; assert(str.size() == 13); }
Output:
before='Short string' after='Short stringX'
See also
(DR*) |
removes the last character (public member function) |