字符串 erase() 函数为类似的调用给出不同的结果
The string erase() function is giving different results for similar calls
我尝试使用带有 2 个参数的string::erase()
函数作为起点和终点,但它为相同类型的调用提供了不同的结果。
这是代码:
#include<iostream>
using namespace std;
int main(){
string s = "azxxzy";
s.erase(2,2);
cout << s;
s.erase(1,1);
cout << endl << s;
}
它删除 2 个字符,即第一次调用xx
,但第二次调用它只删除一个z
。
你能解释一下为什么会这样吗?
更正-
问题是错误的,因为我使用了重载版本,即
'string& erase (size_t pos = 0, size_t len = NPOS(;'
但期望输出
'迭代器擦除(迭代器在前,迭代器在后('
你正在使用 std::string::erase(( 和以下概要:
string& erase (size_t pos = 0, size_t len = npos);
它将擦除在长度len
的位置pos
指定的字符串部分。请注意,仓位索引pos
以 0 开头。len = npos
的默认参数指示直到末尾的所有字符。
在您的示例中,这意味着:
string s = "azxxzy";
s.erase(2,2); /* azzy: deleting 2 characters from position 2 */
s.erase(1,1); /* azy: deleting 1 character from position 1 */
在我的教科书中写道,
std::string::erase
的 2 个参数是iterator first
和iterator last
.这就是为什么我认为它给出了一个奇怪的结果。
你的意思是重载版本:
iterator erase (iterator first, iterator last);
但是您没有提供iterator
.您正在传递int
将隐式转换为size_t
的文本。在我上面发布的链接中,您可以看到重载版本 + 示例。
我希望输出是"ay">
要使用iterator
获得该输出,请使用std::string::begin()
和std::string::end()
执行以下操作:
string s = "azxxzy";
s.erase(s.begin() + 1, s.end() - 1); /* ay: deleting characters */
/* between 1st and last character */
相关文章:
- Doxygen - 如何在不生成图形的情况下生成文本调用关系结果
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- 为什么 std::get<T> 其中 T 是调用 constexpr 函数失败的结果?
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- 字符串 erase() 函数为类似的调用给出不同的结果
- C ++ DLL导入:函数调用返回错误的结果
- 从可调用可变参数元组中的函数结果创建元组
- 如何防止方法的调用方将结果存储在C++中
- OpenGL -- 多个 glDrawArrays() 调用仅显示第一个的结果
- (WMI)ExecMethod out 参数 - 无论调用的结果如何,ResultingSnapshot 都是 NULL
- 有没有办法排除不可调用函数的结果
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 为什么 GCC 调用 libc 的 sqrt() 而不使用其结果?
- 在WINDBG中调用C 方法实例并打印结果
- 为什么我在每个 std::nexttowards 函数调用上都得到相同的结果
- VBA调用相同的C DLL返回不同的结果
- std::具有自定义比较函数结果的排序函数错误:必须调用对非静态成员函数的引用
- 带有unsigned int参数的C++函数在使用negative调用它时会得到奇怪的结果
- 对于相同的输入参数,多个函数调用返回不同的结果
- 使用函数调用结果在C++03中初始化多个成员