Skip to main content

std::string pop_back() method

// Non const version only
void pop_back();

Removes the last character from the string as if by

erase(end()-1)
Undefined Behavior

Calling pop_back() on an empty string is undefined behavior

.

Parameters

(none)

Return value

(none)

Complexity

Constant - O(1).

Exceptions

(none)

Example

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

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

str.pop_back();
std::cout << " after=" << quoted(str) << '\n';
assert(str.size() == 12);

str.clear();
// str.pop_back(); // UB!
}
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 pop_back() method

// Non const version only
void pop_back();

Removes the last character from the string as if by

erase(end()-1)
Undefined Behavior

Calling pop_back() on an empty string is undefined behavior

.

Parameters

(none)

Return value

(none)

Complexity

Constant - O(1).

Exceptions

(none)

Example

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

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

str.pop_back();
std::cout << " after=" << quoted(str) << '\n';
assert(str.size() == 12);

str.clear();
// str.pop_back(); // UB!
}
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.