std::basic_string<CharT,Traits,Allocator>::pop_back

出自cppreference.com
 
 
 
std::basic_string
 
void pop_back();
(C++20 起為 constexpr)

從字符串移除末字符。

等價於 erase(end() - 1)

如果 empty()true,那麼行為未定義。

(C++26 前)

如果 empty()true,那麼:

  • 如果實現是硬化實現,那麼就會發生契約違背
  • 如果實現不是硬化實現,那麼行為未定義。
(C++26 起)

複雜度

常數。

異常

不拋出。

註解

libstdc++ 中,pop_back() 在 C++98 模式中不可用

示例

#include <cassert>
#include <iomanip>
#include <iostream>
#include <string>

int main()
{
    std::string str("Short string!");
    std::cout << "前:" << std::quoted(str) << '\n';
    assert(str.size() == 13);
    
    str.pop_back();
    std::cout << "后:" << std::quoted(str) << '\n';
    assert(str.size() == 12);
    
    str.clear();
//  str.pop_back(); // 未定义行为
}

輸出:

前:"Short string!"
后:"Short string"

缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 出版時的行為 正確行為
LWG 534 C++98 std::basic_string 沒有成員函數 pop_back() 已添加

參閱

後附字符到結尾
(公開成員函數) [編輯]
移除字符
(公開成員函數) [編輯]