gpt4 book ai didi

c++ - std::string::erase() 的 pos 为 string::npos 的定义行为是什么?

转载 作者:行者123 更新时间:2023-11-30 01:49:32 26 4
gpt4 key购买 nike

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

最佳答案

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

21.4.6.5 basic_string::erase [string::erase]

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

Requires: pos <= size()

Throws: out_of_range if pos > size().

Effects: Determines the effective length xlen of the string to be removed as the
smaller of n and size() - pos. The function then replaces the string controlled by *this with a string of length size() - xlen whose first pos elements are a copy of the initial elements of the original string controlled by *this, and whose remaining elements are a copy of the elements of the original string controlled by *this beginning at position pos + xlen.

Returns: *this.

关于c++ - std::string::erase() 的 pos 为 string::npos 的定义行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28953540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com