Difference between revisions of "cpp/string/basic string/pop back"
From cppreference.com
< cpp | string | basic string
(Added a note about the libstdc++ conformance of LWG 534.) |
m ({{ddcla}}) |
||
(2 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
{{cpp/string/basic_string/title|pop_back}} | {{cpp/string/basic_string/title|pop_back}} | ||
{{cpp/string/basic_string/navbar}} | {{cpp/string/basic_string/navbar}} | ||
− | {{ | + | {{ddcla|constexpr=c++20| |
− | + | ||
− | | | + | |
void pop_back(); | void pop_back(); | ||
− | |||
− | |||
}} | }} | ||
− | |||
Removes the last character from the string. | Removes the last character from the string. | ||
Line 33: | Line 28: | ||
|code= | |code= | ||
#include <cassert> | #include <cassert> | ||
− | |||
#include <iomanip> | #include <iomanip> | ||
#include <iostream> | #include <iostream> | ||
+ | #include <string> | ||
int main() | int main() | ||
{ | { | ||
std::string str("Short string!"); | std::string str("Short string!"); | ||
− | std::cout << " | + | std::cout << "Before: " << std::quoted(str) << '\n'; |
assert(str.size() == 13); | assert(str.size() == 13); | ||
str.pop_back(); | str.pop_back(); | ||
− | std::cout << " | + | std::cout << "After: " << std::quoted(str) << '\n'; |
assert(str.size() == 12); | assert(str.size() == 12); | ||
Line 51: | Line 46: | ||
} | } | ||
|output= | |output= | ||
− | + | Before: "Short string!" | |
− | + | After: "Short string" | |
}} | }} | ||
Latest revision as of 14:10, 18 October 2024
void pop_back(); |
(constexpr since C++20) | |
Removes the last character from the string.
Equivalent to erase(end() - 1). The behavior is undefined if the string is empty.
Contents |
[edit] Parameters
(none)
[edit] Return value
(none)
[edit] Complexity
Constant.
[edit] Exceptions
Throws nothing.
[edit] Notes
In libstdc++, pop_back()
is not available in C++98 mode.
[edit] Example
Run this code
#include <cassert> #include <iomanip> #include <iostream> #include <string> int main() { std::string str("Short string!"); std::cout << "Before: " << std::quoted(str) << '\n'; assert(str.size() == 13); str.pop_back(); std::cout << "After: " << std::quoted(str) << '\n'; assert(str.size() == 12); str.clear(); // str.pop_back(); // undefined behavior }
Output:
Before: "Short string!" After: "Short string"
[edit] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 534 | C++98 | std::basic_string did not have the member function pop_back()
|
added |
[edit] See also
appends a character to the end (public member function) | |
removes characters (public member function) |