std::string::erase() 的定义行为是什么,带有 string::npos

What is the defined behavior of std::string::erase() with a pos of string::npos?

本文关键字:string 是什么 npos 带有 erase std 定义      更新时间:2023-10-16

pos参数作为string::npos传递时,C++11 标准为 string& erase (size_t pos = 0, size_t len = npos); 成员函数的行为指定了什么? 我认为它应该什么都不删除,但也许它会抛出一个out_of_range异常? 标准的定义行为是什么?

它抛出std::out_of_range,如标准中明确说明的那样:

21.4.6.5 basic_string::擦除 [字符串::擦除]

basic_string&erase(size_type pos = 0, size_type n = npos);

要求pos <= size()

投掷out_of_range如果pos > size()

效果:确定要删除
的字符串的有效长度xlen作为 较小的nsize() - pos。然后,该函数将替换字符串 由带有一串长度size() - xlen*this控制,其第一个 pos元素是原始字符串的初始元素的副本 由 *this 控制,其其余元素是 原始字符串的元素由 *this 控制,从 位置pos + xlen .

返回*this .

它抛出std::out_of_range .请参阅 http://en.cppreference.com/w/cpp/string/basic_string/erase。

一般原则是 0 到 size() 之间的 pos 值(即超过末尾的一个)是可以的,但超出此值的任何值都表示调用方错误。

相关文章: